首先创建局部组件来完成之间的传值。
父类组件: 使用props属性,父组件向子组件传递数据。
- <div id="app">
- <div>
- <son-boy :obj="obj" :arr="arr">son-boy>
- div>
- div>
-
- <script>
- import SonBoy from "./components/SonBoy.vue";
- export default {
- name: "App",
- data() {
- return {
- obj: {name: "张三",age: 22,sex: "男"},
- arr: [1, 2, 3, 4, 5],
- };
- },
- components: {
- SonBoy,
- },
- };
- script>
- <style>style>
子类组件:
- <div>
- <h2>{{ obj }}h2>
- <h2>{{arr}}h2>
- div>
- <script>
- export default {
- name: "SonBoy",
- props: {
- obj:{
- type:Object
- },
- arr:{
- type:Array
- }
- },
- };
- script>
- <style scoped>style>
子类组件:子组件向父组件传值,使用自定义事件$emit。
在子组件中定义一个方法,使用$emit,'itemclick'是事件名,item是传过去的值。
-
- <div>
- <button
- v-for="(item, index) in categoties"
- @click="hand(item)"
- :key="index"
- >{{item.name}}button>
- div>
- <script>
- export default {
- name: "SonBoder",
- data() {
- return {
- categoties: [
- {id: "aaa",name: "热门推荐"},
- {id: "bbb",name: "手机数码"},
- {id: "ccc",name: "家用家电"},
- {id: "ddd",name: "电脑办公"},
- ],
- };
- },
- methods: {
- hand(item) {
- this.$emit('ageItem',item)
- },
- },
- };
- script>
- <style scoped>style>
父类组类:
- <div id="app">
- <div>
- <son-boder @ageItem="hanger">son-boder>
- div>
- div>
- <script>
- import SonBoder from "./components/SonBoder.vue";
- export default {
- name: "App",
- data() {
- return {
- };
- },
- methods: {
- hanger(item) {
- console.log(item.name);
- },
- },
- components: {
- SonBoder,
- },
- };
- script>
-
- <style>
- style>
兄弟之间传值需要借组bus传递。
新建bus.js用来传递中间的媒介。
- import Vue from 'vue';
- export default new Vue;
创建兄弟1:
-
- <div>
- <button @click="goWork" >传送button>
- div>
- <script>
- import bus from '@/common/bus'
- export default {
- name: "SonBoy",
- data(){
- return{
- msg:'我是兄弟'
- }
- },
- methods: {
- goWork(){
- bus.$emit('SonBoder',this.msg);
- }
- },
- };
- script>
- <style scoped>style>
创建另一个兄弟用来接收数据:
-
- <div>
- {{str}}
- div>
- <script>
- import bus from "@/common/bus";
- export default {
- name: "SonBoder",
- data() {
- return {
- str: "",
- };
- },
- mounted() {
- bus.$on("SonBoder",(data) => {
- this.str = data;
- });
- },
- };
- script>
- <style scoped>style>
