元件傳值之父傳子、子傳父
阿新 • • 發佈:2018-11-09
父元件傳值給子元件
父元件
<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>