创建父子组建,分三步。一是创建文件,二是引入组建,三是组件间通信。在components目录下新建sub文件夹,用于存放一下可以复用的子组件。比如新建一个SubCon.vue组件
<template>
<div class="first-app">{{ msg }}
<button @click="getButtonClick">{{ text || '确认' }}</button>
</div>
</template>
<script>
export default {
name: 'Confirm',
props: ['text'],
data () {
return {msg: 'sub compontsppp'}
},
methods: {
getButtonClick () {
this.$emit('message', this.msg)
}
}
}
</script>
<style scoped>
</style>
父组件的代码如下:
<template>
<div class="hello">
<h1>{{ msg }}</h1>test
<h2>Essential Links</h2>
<Confirm text="注册" @message="getMessage"></Confirm>
</div>
</template>
<script>
import Confirm from './Sub/Confirm'
export default {
name: 'First',
components: {
Confirm
},
data () {
return {
msg: 'Welcome tssso Your Vue.js App111111111'
}
},
methods: {
getMessage (val) {
alert(val)
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
即可创建父子组建,并实现了组建间的通信问题
创建新的组件,在index.js中别忘了添加引入:
import Second from '@/components/Second'