【问题标题】:Props arguments are not reactive in setup道具参数在设置中没有反应
【发布时间】:2021-11-30 05:58:03
【问题描述】:

我正在尝试开发一个编译给定 html 的组件;我成功地使用了恒定的 html 文本,但我无法通过更改 html 文本来完成这项工作。

ma​​in.js

app.component("dyno-html", {
  props: ["htmlTxt"],
  setup(props) {
    watchEffect(() => {
      console.log(`htmlText is: ` + props.htmlTxt);
      return compile(props.htmlTxt);
    });
    return compile(props.htmlTxt);
  },
});

Home.js

<template>
  <div class="home">
    <dyno-html
      :htmlTxt="html2"
      :bound="myBoundVar"
      @buttonclick="onClick"
    ></dyno-html>
    -------------
    <dyno-html
      :htmlTxt="html"
      :bound="myBoundVar"
      @buttonclick="onClick"
    ></dyno-html>
  </div>
</template>

<script>
export default {
  name: "Home",
  components: {},
  data: function() {
    return {
      html: "",
      html2: `<div> Static! <button @click="$emit('buttonclick', $event)">CLICK ME</button></div>`
    };
  },
  mounted() {
    // get the html from somewhere...
    setTimeout(() => {
      this.html = `
        <div>
          Dynamic!
          <button @click="$emit('buttonclick', $event)">CLICK ME</button>
        </div>
      `;
    }, 1000);
  },
  methods: {
    onClick(ev) {
      console.log(ev);
      console.log("You clicked me!");
      this.html2 = "<b>Bye Bye!</b>";
    },
  },
};
</script>

结果:

控制台:

htmlText的变化好像到了setup函数,但不影响compile函数!

【问题讨论】:

    标签: vue.js vuejs3 vue-props


    【解决方案1】:

    这是预期的行为,因为 prop 值被读取一次并导致静态渲染函数。

    属性值应该在渲染函数中读取。它可以用计算来包装以避免不必要的编译器调用:

    const textCompRef = computed(() => ({ render: compile(props.htmlTxt) }));
    return () => h(textCompRef.value);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-22
    • 2018-11-28
    • 2017-11-26
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    相关资源
    最近更新 更多