Vue中常用的几种传值方式

2023-06-20,,

Vue中常用几种传值方式

1. 父传子

父传子的实现方式就是通过props属性,子组件通过props属性接收从父组件传过来的值,而父组件传值的时候使用 v-bind 将子组件中预留的变量名绑定为data里面的数据即可。

父组件代码:

<template>
<div id="container">
<input type="text" v-model="text" @change="dataChange">
<Child :msg="text"></Child>
</div>
</template>
<script>
import Child from "@/components/Child";
export default {
data() {
return {
text: "父组件的值"
};
},
methods: {
dataChange(data){
this.msg = data
}
},
components: {
Child
}
};
</script>
<style scoped>
</style>

子组件代码:

<template>
<div id="container">
{{msg}}
</div>
</template>
<script>
export default {
data() {
return {};
},
props:{
msg: String
}
};
</script>
<style scoped>
#container{
color: red;
margin-top: 50px;
}
</style>

2. 子传父

子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件;子组件给父组件传参用this.$emit(‘事件名’,携带的内容),父组件在相应的位置监听事件

子组件代码:

<template>
<div id="container">
<input type="text" v-model="msg">
<button @click="setData">传递到父组件</button>
</div>
</template>
<script>
export default {
data() {
return {
msg: "传递给父组件的值"
};
},
methods: {
setData() {
this.$emit("getData", this.msg);
}
}
};
</script>
<style scoped>
#container {
color: red;
margin-top: 50px;
}
</style>

父组件代码:

<template>
<div id="container">
<Child @getData="getData"></Child>
<p>{{msg}}</p>
</div>
</template>
<script>
import Child from "@/components/Child";
export default {
data() {
return {
msg: "父组件默认值"
};
},
methods: {
getData(data) {
this.msg = data;
}
},
components: {
Child
}
};
</script>
<style scoped>
</style>

3. 非父子组件间传值

vue提供了很多套组件间传值的方法,父子组件直接用props和$emit就好,大型项目则用vuex,但有一种更适合在小项目中使用的非父子组件传值方法,即bus总线机制。

非父子组件之间传值,需要定义个公共的公共实例文件bus.js,作为中间仓库来传值,不然路由组件之间达不到传值的效果。

公共bus.js

import Vue from 'vue';
let install = (vue) => {
vue.prototype.bus = new Vue();
}
export default install;

3.1 在main.js中引入bus,方便在全局使用:

3.2 接下来就可以在组件A和组件B中使用(例子为兄弟组件传值)

组件A传递:

<template>
<button @click="handle">传递参数</button>
</template>
<script>
export default{
methods:{
handle(){
this.bus.$emit("hello", { obj: 123 });
}
}
}
</script>

组件B接收:

//组件B接受组件A传递来的数据
created() {
this.bus.$on("hello", (data) => {
console.log(data);
});
},

另外一种方法也可以,先从传到父组件,再传到子组件(相当于一个公共bus文件)

4. 路由传参

// 1.命名路由传参
this.$router.push({ name: 'user', params: { user: 'nickname' }});
//页面接受
this.$route.params
// 2.查询参数传参
this.$router.push({path: '/user', query: {user: "nickname"}});
//页面接受
this.$route.query

5. vuex全局使用参数

//新建store.js
import Vue from 'vue'
import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
})
//main.js中引入,就可以全局使用state
import store from './store'
new Vue({
store,
render: h => h(App)
}).$mount('#app');

Vue中常用的几种传值方式的相关教程结束。

《Vue中常用的几种传值方式.doc》

下载本文的Word格式文档,以方便收藏与打印。