vue 父子传值 方法大全

一、通过props传递数据

只能是父控件传递给子控件

父页面

<template>
  <div id="app">
    <!-- <HelloWorld1 width="400" height="500" arr="[1,2,3,4,5]" /> -->
    <HelloWorld1 width=1 height="500" :arr="arr11" ></HelloWorld1>
  </div>
</template>
<script>
import HelloWorld1 from "./HelloWorld1";

export default {
    
    
  data(){
    
    
    return{
    
    
      arr11:[1,2,3,4,5]
    }
  },
  components: {
    
    
    HelloWorld1
  }
};
</script>

子页面

<template>
  <div>
    子控件获取到的值:<br />
    {
    
    {
    
     width }}<br />
    {
    
    {
    
     height }}<br />
    {
    
    {
    
    arr}}
  </div>
</template>>

<script>
export default {
    
    
  props: {
    
    
    width: {
    
    
      //接受类型
      type: String,
      //false 可以为空 .true 不能为空 报错但不影响显示
      required: false,
      //默认值
      default: "800",
    },
    height: {
    
    
      //接受类型(多种类型)
      type: [Number, String],
    },
    arr: {
    
    
      type: Array,
      required: true,
    },
  },
};
</script>

二、子控件给父控件传递值

父页面

<template>
  <div id="app">
    点击按钮我就从500变成了800<br/> {
    
    {
    
    width}}
    <hr>
    <HelloWorld1 @myChange111="dochange" />
  </div>
</template>
<script>
import HelloWorld1 from "./HelloWorld1";

export default {
    
    
  name: 'App',
  data(){
    
    
    return{
    
    
        width:500
    }
  },methods:{
    
    
    dochange(val){
    
    
      this.width=val;
    }
  },
  components: {
    
    
    HelloWorld1
  }
}
</script>

子页面

<template>
  <div>
    <button @click="dochange()">ahahha</button>
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    };
  },
  methods: {
    
    
    dochange() {
    
    
      this.$emit("myChange111", 800);
    },
  },
};
</script>

三、插槽slot

vue 插槽的使用

四、vuex

vuex 简单的 state与mutations 操作

猜你喜欢

转载自blog.csdn.net/xiaozhezhe0470/article/details/108987587