这种环境下可以行使中央变乱总线的方法。新建一个Vue变乱bus工具,然后通过bus.$emit触发变乱,bus.$on监听触发的变乱。
- Vue.component('brother1',{
- data(){
- return {
- myMessage:'Hello brother1'
- }
- },
- template:`
- <div>
- <p>this is brother1 compoent!</p>
- <input type="text" v-model="myMessage" @input="passData(myMessage)">
- </div>
- `,
- methods:{
- passData(val){
- //触发全局变乱globalEvent
- bus.$emit('globalEvent',val)
- }
- }
- })
- Vue.component('brother2',{
- template:`
- <div>
- <p>this is brother2 compoent!</p>
- <p>brother1转达过来的数据:{{brothermessage}}</p>
- </div>
- `,
- data(){
- return {
- myMessage:'Hello brother2',
- brothermessage:''
- }
- },
- mounted(){
- //绑定全局变乱globalEvent
- bus.$on('globalEvent',(val)=>{
- this.brothermessage=val;
- })
- }
- })
- //中央变乱总线
- var bus=new Vue();
- var app=new Vue({
- el:'#app',
- template:`
- <div>
- <brother1></brother1>
- <brother2></brother2>
- </div>
- `
- })
6. parent和children
- Vue.component('child',{
- props:{
- value:String, //v-model会自动转达一个字段为value的prop属性
- },
- data(){
- return {
- mymessage:this.value
- }
- },
- methods:{
- changeValue(){
- this.$parent.message = this.mymessage;//通过云云挪用可以改变父组件的值
- }
- },
- template:`
- <div>
- <input type="text" v-model="mymessage" @change="changeValue">
- </div>
- })
- Vue.component('parent',{
- template:`
- <div>
- <p>this is parent compoent!</p>
- <button @click="changeChildValue">test</button >
- <child></child>
- </div>
- `,
- methods:{
- changeChildValue(){
- this.$children[0].mymessage = 'hello';
- }//在此我向各人保举一个前端全栈开拓交换圈:619586920 打破技能瓶颈,晋升思想手段
- },
- data(){
- return {
- message:'hello'
- }
- }
- })
- var app=new Vue({
- el:'#app',
- template:`
- <div>
- <parent></parent>
- </div>
- `
- })
7. boradcast和dispatch (编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|