javascript - Vue渲染按钮

标签 javascript vue.js vuejs2 vue-component

我的问题是关于在 vue 实例上渲染一个按钮,单击一个按钮,然后通过事件单击渲染另一个按钮,如果我简单地安装按钮,它不会获得函数 tes。

const Hello = {
  props: ['text'],
  template: '<button v-on:click="tes"> </button> ',
};

new Vue({
  el: '#app',
  data: {
    message: 'Click me'
  },
  methods:{
        alertar: function(event){
                      const HelloCtor = Vue.extend(Hello);
            var instance = new HelloCtor({
                    propsData: {
                  text: 'HI :)'
                }
            })

                instance.$mount() // pass nothing
           this.appendChild(instance.$el)
      },
      tes: function(){
            alert('Teste');
      }
  }
})

错误:

vue.js:597 [Vue warn]: Invalid handler for event "click": got undefined

(found in <Root>)
warn @ vue.js:597
(index):52 Uncaught TypeError: this.appendChild is not a function
    at Vue.alertar ((index):52)
    at invoker (vue.js:2029)
    at HTMLParagraphElement.fn._withTask.fn._withTas

最佳答案

问题是您在父 Vue 内部创建了一个子组件,其中包含绑定(bind)到 tes 函数的模板。这意味着子进程将在自己的方法中查找 tes,但它是父进程的属性,而不是子进程本身的属性,因此它永远无法在自己的作用域中找到它。您必须将该函数添加到子组件中:

const Hello = {
  props: ['text'],
  template: '<button v-on:click="tes"> </button> ',
  methods: {
    tes: function(){
      alert('Teste');
    }
  }
};

关于javascript - Vue渲染按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50875369/

相关文章:

javascript - Laravel Ajax 分页链接在第二页点击刷新

vue.js - Vue 3-Vuetify 3 : color--text not working

vue.js - 如果值为空则跳过对象项

vue.js - 我可以对 v-model 使用条件运算吗?

javascript - VueJS 获取数据作为对象

javascript - asp.net mvc 6 web api + Angular 资源帖子数组作为对象属性

javascript - 当我在 Javascript 中使用原型(prototype)向一个对象添加数组时,该对象的所有实例就像它们共享一个数组一样

javascript - 如何对 AngularJS 服务/工厂进行单元测试

当输入字段的数量不恒定时,Vue.js如何从输入字段收集值

javascript - 如何在Vue js中计算折扣