版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cristina_song/article/details/83032447
父组件传值给子组件
父组件
<template>
<div id="app">
<h1>props使用方式</h1>
<hello txt='组件txt' v-bind:ddd="btnText"></hello>
<p><input type="text" v-model="btnText"></p>
</div>
</template>
<script>
import hello from './components/hello.vue'
export default {
name:'app',
components:{hello},
data(){
return{
btnText:"Hello World"
}
}
}
</script>
子组件
<template>
<div id="hello">
<button>{{txt}}</button>
<p>{{ddd}}</p>
</div>
</template>
<script>
export default {
name:'hello',
props:[//父传子
'txt',
'ddd'
],
}
</script>
<style>
#hello button{
background-color: red;
width: 200px;
height: 50px;
}
</style>
子组件传值给父组件
父组件
<template>
<div id="app">
父组件:
<span>{{name}}</span>
<br>
<br>
<!-- 引入子组件 定义一个on的方法监听子组件的状态-->
<child v-on:childByValue="childByValue"></child>
</div>
</template>
<script>
import child from './components/child.vue'
export default {
name:'app',
components:{child},
data () {
return {
name: ''
}
},
methods: {
childByValue: function (childValue) {
// childValue就是子组件传过来的值
this.name = childValue
}
}
}
</script>
子组件
<template>
<div id="child">
子组件:
<span>{{childValue}}</span>
<!-- 定义一个子组件传值的方法 -->
<input type="button" value="点击触发" @click="childClick">
</div>
</template>
<script>
export default {
name:'child',
data () {
return {
childValue: '我是子组件的数据'
}
},
methods: {
childClick () {
// childByValue是在父组件on监听的方法
// 第二个参数this.childValue是需要传的值
this.$emit('childByValue', this.childValue)
}
}
}
</script>