1 定义一个全局的子组件
<template> <div> <img src="../assets/logo.png" alt=""> <div>{{mymsg}}</div> </div> </template> <script> export default { props:['mymsg'], } </script>在父组件引用子组件
<template> <div class="about"> <h1>This is an about page</h1> <msg :mymsg="123"></msg> </div> </template> <script> import msg from '../components/shopimg' export default { components:{msg}, data(){ return{ messages:'123' } }, } </script>注意: 1 在父组件声明子组件 import 组件名 from ‘…/组件.vue’; 子组件的位置 2 components 里面写上子组件的名称 就是important 后面的名字 3 用components 里面的名字就相对于标签 可以在父组件中使用 4 父组件到子组件的传值就是直接 props传值 在父组件中绑定子组件定义的props属性 就可以实现父到子传值了
子: 触发自定义事件 this.$emit(‘自定义事件名’,参数列表,…);
<template> <div class="home"> <h1>父组件</h1> <child @list='show'></child> </div> </template> <script> // @ is an alias to /src import child from '../views/About' export default { components:{child}, data(){ return { } }, methods:{ show(val){ console.log(123) } } } </script>1 在父组件声明子组件 import 组件名 from ‘…/组件.vue’; 子组件的位置 2 components 里面写上子组件的名称 就是important 后面的名字 3 <子组件 @自定义事件名=“父自己方法”></子组件>
思路: VUE–组件
xxx.vue–文件名 结构: 三部分 主页面 html… 注意:1:必须有根元素 class 2:根元素只能有一个
组件的使用: 1:路由关联组件 2:组件的通讯 1)父子组件:
父—>子
子组件:
export default { props:[‘属性名’,…], }
父组件:
import 组件名 from ‘@/components/Mine/组件.vue’; …
组件一个实例 <组件名 v-for=“n of 10” :msg=“n”></组件名>
export default { components: { 组件名,… }, }
2)子–>父 父: 要给子定义自定义事件 <子组件 @自定义事件名=“父自己方法”></子组件>
子: 触发自定义事件 this.$emit(‘自定义事件名’,参数列表,…);
父 到 子 传值 绑定的值要和子组件声明的属性一直 就是(props) 3)兄弟组件通讯 1: 子- e m i t − 父 − p r o p s − 子 2 : 子 − t h i s . emit-父-props-子 2: 子-this. emit−父−props−子2:子−this.parent-父的方法-props-另一个子的属性 <组件 ref=“组件指针”></组件> 3: 子-this. p a r e n t − 父 的 方 法 − t h i s . parent-父的方法-this. parent−父的方法−this.refs.组件指针-另一个子的属性 4:总线方式: 1)建立vue总线对象 Bus.js import Vue from ‘vue’
export default new Vue();
2)两个子组件都去引用这个Bus
A(发送者)
Bus.$emit(‘sendMsg’,‘您好’);
B(接受者)
created(){ Bus.$on(‘sendMsg’,(msg)=>{ this.msg = msg; }); },
?5: