vue組件之間傳值方式解析

vue組件之間傳值方式解析
一.父組件傳到子組件
1.父組件parent代碼以下:
<template>
<div class="parent">
<h2>{{ msg }}</h2>
<son psMsg="父傳子的內容:叫爸爸"></son> <!-- 子組件綁定psMsg變量-->
</div>
</template>
<script>
import son from './Son' //引入子組件
export default {
name: 'HelloWorld',
data () {
return {
msg: '父組件',
}
},
components:{son},
}
</script>
2.子組件son代碼以下:
<template>
<div class="son">
<p>{{ sonMsg }}</p>
<p>子組件接收到內容:{{ psMsg }}</p>
</div>
</template>
<script>
export default {
name: "son",
data(){
return {
sonMsg:'子組件',
}
},
props:['psMsg'],//接手psMsg值
}
</script>
3.效果圖以下:

二.子組件向父組件傳值
經過綁定事件而後及$emit傳值
1.父組件parent代碼以下
<template>
<div class="parent">
<h2>{{ msg }}</h2>
<p>父組件接手到的內容:{{ username }}</p>
<son psMsg="父傳子的內容:叫爸爸" @transfer="getUser"></son> <!--綁定自定義事件transfer-->
</div>
</template>
<script>
import son from './Son'
export default {
name: 'HelloWorld',
data () {
return {
msg: '父組件',
username:'',
}
},
components:{son},
methods:{
getUser(msg){
this.username= msg
}
}
}
</script>
2.子組件son代碼以下:
<template>
<div class="son">
<p>{{ sonMsg }}</p>
<p>子組件接收到內容:{{ psMsg }}</p>
<!--<input type="text" v-model="user" @change="setUser">-->
<button @click="setUser">傳值</button>
</div>
</template>
<script>
export default {
name: "son",
data(){
return {
sonMsg:'子組件',
user:'子傳父的內容'
}
},
props:['psMsg'],
methods:{
setUser:function(){
this.$emit('transfer',this.user)//將值綁定到transfer上傳遞過去
}
}
}
</script>
3.效果圖以下:

3、經過Vuex狀態管理傳值
1.經過npm加載vuex,建立store.js文件,而後在main.js中引入,store.js文件代碼以下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const state = {
author:'Wise Wang'
};
const mutations = {
newAuthor(state,msg){
state.author = msg
}
}
export default new Vuex.Store({
state,
mutations
})
2.父組件parent代碼以下:
<template>
<div class="parent">
<h2>{{ msg }}</h2>
<p>父組件接手到的內容:{{ username }}</p>
<input type="text" v-model="inputTxt">
<button @click="setAuthor">傳參</button>
<son psMsg="父傳子的內容:叫爸爸" @transfer="getUser"></son>
</div>
</template>
<script>
import son from './Son'
export default {
name: 'HelloWorld',
data () {
return {
msg: '父組件',
username:'',
inputTxt:''
}
},
components:{son},
methods:{
getUser(msg){
this.username= msg
},
setAuthor:function () {
this.$store.commit('newAuthor',this.inputTxt)
}
}
}
</script>
3.子組件son代碼以下:
<template>
<div class="son">
<p>{{ sonMsg }}</p>
<p>子組件接收到內容:{{ psMsg }}</p>
<p>這本書的做者是:{{ $store.state.author }}</p>
<!--<input type="text" v-model="user" @change="setUser">-->
<button @click="setUser">傳值</button>
</div>
</template>
<script>
export default {
name: "son",
data(){
return {
sonMsg:'子組件',
user:'子傳父的內容'
}
},
props:['psMsg'],
methods:{
setUser:function(){
this.$emit('transfer',this.user)
}
}
}
</script>
4.效果圖以下:
相關文章
相關標籤/搜索