Vue必备(marksheng)
1.插槽
匿名插槽:子组件
父组件 今天天气阳光明媚 具名插槽:子组件
父组件 今天天气挺好
作用域插槽:
子组件
父组件
{ {scope.nickName}}
2.封装组件
首先,使用Vue.extend()创建一个组件
然后,使用Vue.component()方法注册组件
接着,如果子组件需要数据,可以在props中接受定义
最后,子组件修改好数据之后,想把数据传递给父组件,可以使用emit()方法
3.vue六种传值方式(属性传值、$refs、$parent、通知传值(广播传值)、本地传值、路由传值)
在介绍组件传值之前先明确三种组件关系:父子组件、兄弟组件、表兄弟组件(a1,a2,a3 | a1和a3)、无关系组件(a,b)
1.属性传值:父传子
可传值类型:固定值 绑定属性 方法 本类对象
父:
子:
props:{
'mess':String, 'bindMsg':\[String, Number\], 'run':Function, 'fatherThis':Object,
}
可传值类型:属性 方法
2.$refs:子传父与vue获取元素ref=”dataNum”(this.$refs.dataNum.dataset.num)
父:
使用:this.$refs.header.msg this.$refs.header.属性
this.$refs.header.方法子:data(){ return{ msg:”我是子组件header的值哟” } }
vue获取元素:
55
this.$refs.dataNum.dataset.num
3.$parent:父传子
可传值类型:属性 方法
直接在子组件中使用
this.$parent.XX
,不需要做任何多余操作子 :getFatherProp(){
alert(this.$parent.fatherMsg);
},
4.兄弟传兄弟————通知传值(广播传值)
只传基本数据类型,不能传方法。
传输:通过 bus.$emit(‘名称’,’数据’)传播数据
接收:bus.$on(‘名称’,function(){})
示例:example
定义bus.js文件:import Vue from ‘vue’ var bus= new Vue(); export default bus;
然后引入:import vueEvents from ‘../Model/vueEvent.js’
5.本地传值(localStorage和vuex都是本地存储)
本地传值方式对于Vue而言有两种,一种是JS的
localStorage
,另一种Vuex
。
- localStorage
存:
localStorage.setItem(‘tolist’,JSON.stringify(this.tolist));
取:var tolist = JSON.parse(localStorage.getItem(‘tolist’));
Vuex
使用数据:this.\$store.state.count
调用方法:this.$store.commit('incCount');
1.定义存储数据 var state = { count:1,}
2. //类似于计算属性 state里边的数据改变时候触发的方法。 可以做一些操作 并且可以有返回值 var getterfl={ completedCountChange(state){ return state.count * 2 +'位'; } } 3.Action 类似于 mutation,不同在于: Action 提交的是 mutation,而不是直接变更状态。Action 可以包含任意异步操作
var actionfl = {
asynIncCount(context){
//因此你可以调用context.commit来提交一个mutation 使用action需要用dispatchcontext.commit('incCount');
}
}6.路由传值(this.$router.push)
1.父组件push使用this.$router.push
2.在子组件中获取参数的时候是this.$route.params1.动态路由传值
1.1 配置动态路由 routes:[ //动态路由参数 以冒号开头 {path:'/user/:id',conponent:User} ] 1.2 传值 第一种写法 : <router-link :to="'/user/'+item.id">传值</router-link> 第二种写法 : goToUser(id) { this.$router.push( {path:'/user/'+id}); } 1.3 在对应页面取值 this.$route.params; //结果:{id:123}
Get传值(类似HTMLGet传值)
2.1 配置路由
const routes = [{path:'/user',component:User},]
2.2 传值
第一种写法 : <router-link :to="'/user/?id='+item.id">传值</router-link> 第二种写法 : goToUser(id) { //'user' 是路径名称 this.$router.push({path:'user',query:{ID:id}}); }
2.3 在对应页面取值
this.$route.query; //结果 {id:123}
命名路由push传值
3.1 配置路由
const routes = [{path:'/user',name: 'User',component:User},]
3.2 传值
goToUser(id) { //'User' 是路径重命名 this.$router.push({name:'User',params:{ID:id}}); }
3.3 在对应页面取值
this.$route.params; //结果:{id:123}
还没有评论,来说两句吧...