通信vue2.0组件

2022-10-15,,

vue2.0组件通信各种情况总结与实例分析

 

Props在vue组件中各种角色总结

在Vue中组件是实现模块化开发的主要内容,而组件的通信更是vue数据驱动的灵魂,现就四种主要情况总结如下:

使用props传递数据---组件内部

//html
<div id="app1">
<i>注意命名规定:仅在html内使用my-message</i>
<child my-message="组件内部数据传递"></child>
</div>
//js
<script>
Vue.component('child', {
props: ['myMessage'],
template: '<mark>{{ myMessage }}<mark/>'
});
new Vue({
el: '#app1'
})
</script>

动态props通信---组件与根节点(父子之间)

<div id="app2">
<input v-model="parentMsg">
<br>
<child :parent-msg="parentMsg"></child>
</div>
<script>
Vue.component('child', {
props: ['parentMsg'],
template: '<mark>{{ parentMsg }}<mark/>'
});
new Vue({
el: '#app2',
data: {
parentMsg: 'msg from parent!'
}
})
</script>

对比分析:

例子1:

<comp some-prop="1"></comp>
//组件内部数据传递,对应字面量语法:传递了一个字符串"1"

例子2:

<comp v-bind:some-prop="1"></comp>
//组件与根节点数据传递,对应动态语法:传递实际的数字:js表达式

单向数据流动特点:父组件属性变化时将传导给子组件,反之不可

两种改变prop情况

注意在 JavaScript 中对象和数组是引用类型,指向同一个内存空间,如果 prop 是一个对象或数组,在子组件内部改变它会影响父组件的状态。

//定义一个局部data属性,并将 prop 的初始值作为局部数据的初始值
props: ['initialCounter'],
data: function () {
return { counter: this.initialCounter }
}
//定义一个局部computed属性,此属性从 prop 的值计算得出
props: ['size'],
computed: {
normalizedSize: function () {
return this.size.trim().toLowerCase()
}
}

子组件索引

尽管有 props 和 events ,但是有时仍然需要在 JavaScript 中直接访问子组件。为此可以使用 ref 为子组件指定一个索引 ID

<div id="parent">
<!-- vm.$refs.p will be the DOM node -->
<b ref="p">hello</b>
<!-- vm.$refs.child will be the child comp instance -->
<user-profile v-for='i in 3' ref="profile"></user-profile>
</div>
<script>
var userPf=Vue.component('user-profile',{
template:'<div>hello $refs</div>'
});
var parent = new Vue({ el: '#parent' });
// 访问子组件
var child = parent.$refs.profile;
console.log(child[0]);
console.log(parent.$refs.p);
</script>

$refs 只在组件渲染完成后才填充,并且它是非响应式的。它仅仅作为一个直接访问子组件的应急方案——应当避免在模版或计算属性中使用 $refs 。

数据反传---自定义事件

自定义事件的根基在于每个vue实例都实现了事件接口(Event interface)
Vue的事件系统分离自浏览器的EventTarget API。尽管它们的运行类似,但是$on 和 $emit 不是addEventListener 和 dispatchEvent 的别名。
父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件

监听:$on(eventName)

触发:$emit(eventName)

<div id="app3">
<p>Look at the parent's data: <mark>{{t}}</mark> & the child's data: <mark>{{childWords}}</mark></p>
<child v-on:add="pChange"></child>
<child v-on:add="pChange"></child>
<child v-on:click.native="native"></child>
</div>
<script>
Vue.component('child', {
template: `<button @click="add">{{ c }}</button>`,
data: function () {
return {
c: 0,
msg: 'I am from child\'s data'
}
},
methods: {
add: function () {
this.c += 1;
this.$emit('add',this.msg);
}
},
});
new Vue({
el: '#app3',
data: {
t: 0,
childWords: ''
},
methods: {
pChange: function (msg) {
this.t += 1;
this.childWords=msg;
},
native:function () {
alert('I am a native event ,which comes from the root element!');
}
}
})
</script>

兄弟间通信---简单场景用bus,复杂场景用vuex

<div id="app4">
<display></display>
<increment></increment>
</div>
<script>
var bus = new Vue();
Vue.component('increment', {
template: `<button @click="add">+</button>`,
data: function () {
return {count: 0}
},
methods: {
add: function () {
bus.$emit('inc', this.count+=1)
}
}
});
Vue.component('display', {
template: `<span>Clicked: <mark>{{c}}</mark> times</span>`,
data: function () {
return {c: 0}
},
created: function () {
var self=this;
// bus.$on('inc', function (num) {
// self.c = num
// });
bus.$on('inc', (num) =>
this.c = num
);
}
});
vm = new Vue({
el: "#app4",
})
</script>

总结:Vue中关于组件间及组件与根节点间通信都可以人为是父子兄弟间的通信,另外父子关系是相对的即与上下文有关(比如A组件的父组件可能是B组件的子组件);上述四个例子分别演示了不同组件通信的机制。
澄清了上述问题不难理这句话:
编译作用域---父组件模板的内容在父组件作用域内编译;子组件模板的内容在子组件作用域内编译。分发内容是在父组件作用域内编译

 

 
标签: vue2.0组件通信各种情况总结与实例分析

通信vue2.0组件的相关教程结束。

《通信vue2.0组件.doc》

下载本文的Word格式文档,以方便收藏与打印。