首页 > 解决方案 > 是否可以将对象中的 Vue/Javascript 代码发送到另一个组件?

问题描述

我有一个父子Vue组件。子组件为父组件提供渲染页面所需的数据,该数据使用一个简单的对象发出,该对象使用emit.

子组件数据:

   const Steps [
      {
            sequence: 1,
            name: "Personal",
            description: `<p>Enter your name and phone number</p>`,
          },
      {
            sequence: 2,
            name: "OTP",
            description: `<p>An OTP code has been sent to you. Resend code</p>`,
          },
    ]

const SelectedStep = ref( 0 ); // Which step did you select?
const ActiveStep = ref( {} );  // What step is the form currently on?


SelectedStep.value += 1; // e.g. SelectedStep.value === 2

// Get the object in Steps array where the sequence === 2
ActiveStep.value = Steps.find(step => {
        return step.sequence === SelectedStep.value
      })

// Send this to the parent to render the description and title
emit('SelectedStep', ActiveStep.value);

根据sequence所选择的,Steps匹配该序列值的对象将被加载到ActiveStep. 然后将其发射/提供给父组件。

但是,如果您查看sequence: 2上面的对象,则其中descriptionresend code文本。我需要将其作为绑定链接,以便在单击它时运行一个函数以重新发送代码。我想象过这样的事情:

{
        sequence: 2,
        name: "OTP",
        description: `<p>An OTP code has been sent to you. <a v-on:click="resendOTP">Resend code</a></p>`,
      },

当它在页面上呈现时,v-on:click它不会被解释并在 HTML 中按原样呈现。

父组件只是一个使用该组件的视图:

    <header>
    <h1>{{ActiveStep.title}}</h1>
    <div v-html="`${ActiveStep.description}`">{{ActiveStep.description}}</div>
    </header>
    <div>
          <div class="content">
            <Component-Signup v-on:SelectedStep="updateActiveStep"/>
          </div>
       </div> 
    
    <script>
    import ComponentSignup from "../../components/Signup.vue"
    
    export default {
    components: {
    "Component-Signup": ComponentSignup
  },
    setup() {
    const ActiveStep = ref({});
        
    function updateActiveStep(SelectedStep) {
          ActiveStep.value = SelectedStep // SelectedStep is the object emitted from child component
         }
    
    return {
          updateActiveStep,
          ActiveStep
        }
    }
}
    </script>

这怎么可能实现?

标签: javascriptvue.jsvuejs3

解决方案


首先,您description包含 HTML,因此插值 ( {{ }}) 不会像您期望的那样显示它......它将被编码显示

v-html指令可用于呈现原始 HTML

v-html仅对 HTML 有用。任何与 Vue 相关的功能 (as v-on) 都将不起作用。文件:

请注意,您不能使用v-html组合模板部分,因为 Vue 不是基于字符串的模板引擎。相反,组件更适合作为 UI 重用和组合的基本单元。

您唯一的选择是为每个步骤创建单独的组件,并使用当前步骤显示正确的组件...


推荐阅读