vue脚手架中父子组件传值

2020-05-14  本文已影响0人  五四青年_4e7d

组件直接引入展示:

简单理解:这个就是把子组件的内容原封不动的显示在父组件

  //抽离引入
import shoplist from "./list.vue";
//和data同级:
components: 
    shoplist,
  },
<template>
  <div class="hello">
   <shoplist></shoplist>
  </div>
</template>
image.png

父组件向子组件传值:

父组件:

<template>
  <div class="hello">
    <!-- 传两个值 -->
   <shoplist :title="msg" :text="flg"></shoplist>
  </div>
</template>

<script>
//引入子组件
import shoplist from "./list.vue";
export default {
 components: {
     //映射为组件
    shoplist,
  },
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      flg:123
    }
  }
}
</script>

子组件内部:

<template>
  <div class="hello">子组件内容{{title}}{{text}}</div>
</template>
<script>
export default {
  props: { title: String, text: Number },
  data() {
    return {};
  }
};
</script>
image.png

子向父传值

<template>
  <div class="hello">
    <h1>{{num}}</h1>
    <!-- 传两个值 -->
    <shoplist :title="msg" :text="flg" @sonTate="state"></shoplist>
  </div>
</template>

<script>
//引入父组件
父组件:
import shoplist from "./list.vue";
export default {
  components: {
    //映射为组件
    shoplist
  },
  data() {
    return {
      msg: "Welcome to Your Vue.js App",
      flg: 123,
      num: ""
    };
  },
  methods: {
    state(a) {
      this.num = a;
    }
  }
};
</script>

子组件:

<template>
  <div class="hello">
    子组件内容{{title}}{{text}}
    <button @click="info">按钮</button>
  </div>
</template>

<script>
export default {
  props: { title: String, text: Number },

  data() {
    return {
      item: "公司"
    };
  },
  methods: {
    info() {
      this.$emit("sonTate", this.item);
    }
  }
};
</script>

image.png
上一篇 下一篇

猜你喜欢

热点阅读