Vue根据条件props传值

587 阅读1分钟

一、场景需求

根据不同的条件,父组件通过props传值给子组件。props的参数名称不变(都用msg)

二、实现方法一

定义一个新的变量 needProps 控制传的是哪个值,根据条件设置needProps的值,再根据needProps决定传的是哪个数组
:msg="needProps ? msg : msg2"

父组件:

<template >
  <div class="nav">
    <input type="text" placeholder="请选择" v-model="selectValue" />
    <HelloWorld :msg="needProps ? msg : msg2" @select="change" />
  </div>
</template>
<script>
import HelloWorld from "@/components/HelloWorld.vue";
export default {
  components: { HelloWorld },
  data() {
    return {
      needProps: true,
      show: false,
      selectValue: "",
      msg: [
        { name: "一一", country: "中国" },
        { name: "二二", country: "中国" },
        { name: "三三", country: "中国" },
        { name: "四四", country: "中国" },
      ],
      msg2: [{ name: "一一", country: "中国" }],
    };
  },
  methods: {
    change(value) { //子组件的$emit传的第二个参数就是value
      this.selectValue = value;
      if (this.selectValue === "一一") {
        this.needProps = false;
      }
    },
  },
};
</script>

子组件:正常接收

<template>
  <div class="hello">
    <ul v-for="(item, index) in msg" :key="index">
      <li @click="selectLi(item)">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {};
  },
  props: {
    msg: {
      type: Array,
      default: () => [], //重点
    },
  },
  methods: {
    selectLi(item) {
      this.$emit("select", item.name);
    },
  },
};
</script>

三、实现方法二

在methods里面根据条件判断之后直接把传过去的msg用msg2替换掉。
父组件

...与方法二一致,省略
  methods: {
    change(value) {
      this.selectValue = value;
      if (this.selectValue == "一一") {
        this.msg = this.msg2;
      }
      console.log(value);
    },
  }

四、实现效果

如果不选“一一”,列表还显示四个选项 image.png

如果选择了“一一”,列表只显示一个选项 image.png