vue组件通信&如何运行单个.vue文件

如果vue文件可以像html那样直接运行在浏览器,不需要安装任何插件就好了。

没成功

  • 尝试二:通过npm i -g @vue/cli-service-global
    vue serve 文件.vue
    成功了

组件通信

1.父子组件之间

  • 父给子传值,子通过props接收。

这是我写的App.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<template>
<div>
<h1>我是{{name}}</h1>
<son v-bind:message="parentMsg"></son> //通过v-bind实现动态绑定,子收到的消息是good good study
//不写v-bind:的时候,子收到的消息是partMsg
</div>
</template>

<script>
import Son from './components/Son'
export default {
components: { Son },
name: 'App',

data() {
return {
name:"your father",
parentMsg:"good good study"

};
}
};
</script>

<style lang="scss" scoped>

</style>

这是我写的Son.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
<div>
<h2>我是{{name}}</h2>
<p>{{message}}</p>
</div>
</template>

<script>
export default {
name: 'Son',
props:["message"], //接收父传来的message
data() {
return {
name:"your son or daughter"
};
}
};
</script>

<style lang="scss" scoped>

</style>
  • 子给父传值 $emit

这是我写的App.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<template>
<div>
<h1>我是{{name}}</h1>
<son v-on:listenMsg="showMsg"></son>
</div>
</template>

<script>
import Son from './components/Son'
export default {
components: { Son },
name: 'App',

data() {
return {
name:"your father"
};
},
methods: {
showMsg(data){
console.log(data);
}
}
};
</script>

<style lang="scss" scoped>

</style>

这是我写的Son.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<template>
<div>
<h2>我是{{name}}</h2>
<button @click="sendToFa">子给父传值</button>
</div>
</template>

<script>
export default {
name: 'Son',
methods:{
sendToFa(){
this.$emit('listenMsg', "I have no money , love you dad"); //事件名,参数
}
},
data() {
return {
name:"your son or daughter"
};
}
};
</script>

<style lang="scss" scoped>

</style>

小结:
相信大家也发现了,子组件在给父组件传值的时候,是通过事件驱动的。那么,如果不利用事件驱动,可以进行传值吗?可以(vuex或者异步)

2.兄弟组件之间

方式一:创建一个共同中间组件,太麻烦
方式二:

1
2
3
4
5
6
7
8
//新建一个Vue实例
let event = new Vue()

//监听事件
event.$on('eventname',(val) => {})

//触发事件
event.$emit('eventname','this is a message')

中央事件总线插件vue-bus

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//vue-bus.js
const install = function (Vue) {
const Bus = new Vue({
methods: {
emit (event,...args) {
this.$emit(event,...args)
},
on (event,callback) {
this.$on(event,callback)
},
off (event,callback) {
this.$off(event,callback)
}
}
})
Vue.prototype.$bus = Bus
}
export default install

使用vue-bus有两点注意

  • $bus.on写在created钩子内

    因为写在mounted内使用,可能接收不到其他组件来自created钩子内发出的事件

  • 使用了$bus.on,在beforeDestroy钩子里应该用$bus.off解除

    因为组件销毁后,没必要把监听的句柄存储在vue-bus里

父链和子组件索引

在子组件中,使用this.$parent可以直接访问该组件的父实例或组件,父组件也可以通过this.$children访问它所有的子组件,而且可以递归向上或向下无限访问,直到根实例或最内层的组件

当子组件较多时,通过this.$children来一一遍历出我们需要的组件实例是困难的,尤其组件渲染的时候,它们的序列不固定。Vue提供子组件索引的方法,用特殊的属性ref来为子组件指定一个索引名称。

在父组件模板中,子组件标签上使用ref指定一个名称,并在父组件内通过this.$refs来访问指定名称的子组件。

$refs只在组件渲染完成之后才填充,并且它是非响应式的