【问题标题】:How to trigger the method on parent component from child using render function in Vuejs 3如何使用 Vuejs 3 中的渲染函数从子组件触发父组件的方法
【发布时间】:2021-02-05 09:31:27
【问题描述】:

在本例中如何从ComponentA 触发app2 上的clicked 方法。

const app = Vue.createApp({});

app.component('ComponentA', {
    template: `<button @click="clicked" class='btn'>Click</button>`
});

const app2 = Vue.createApp({
   methods: {
     clicked() {
        this.clickCount += 1;
     }
   },

   render() {
     return Vue.h(app.component('ComponentA'), options);
   }
}).mount("#App");
            

【问题讨论】:

    标签: javascript vue.js vue-component vuejs3


    【解决方案1】:

    从按钮单击事件处理程序尝试发出一个名为 clicked 的事件,在渲染函数中通过在其前面加上 on 和大写首字母(如 onClicked: (e) =&gt; {...})在此函数的主体内运行 @987654324 来定义它@

    let options = {}
    options.baseUrl = "someurl.com";
    
    const app = Vue.createApp({})
    app.component('ComponentA', {
      template: `
            <button @click="$emit('clicked')" class='btn'>Click</button>
        `
    });
    
    const app2 = Vue.createApp({
      methods: {
        clicked() {
          console.log("clicked !!!")
          this.clickCount += 1;
        }
      },
      render() {
        return Vue.h(app.component('ComponentA'), {
          onClicked: (e) => {
    
            this.clicked()
          }
        }, options)
      }
    }).mount("#app");
    <script src="https://unpkg.com/vue@3.0.0-rc.11/dist/vue.global.prod.js"></script>
    
    <div id="app" someVariable='some value'>
    
    
    </div>

    【讨论】:

    • 点击按钮时可以改变baseUrl的值吗?
    • 它应该在 data 选项中定义,正如我在其他答案中所建议的那样
    猜你喜欢
    • 2021-12-01
    • 2021-11-28
    • 1970-01-01
    • 2021-02-12
    • 2022-10-04
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多