Vue.js动态添加和删除

时间:2017-06-17 18:22:03

标签: javascript vue.js vuejs2

我正在为我的游戏学习Vue.js,我想知道是否有办法动态添加和删除Vue.js中的组件? 这是我当前的代码

var vue = new Vue({
    el: "#fui",
    template: ``
})

const HelloCtor = Vue.extend({
  props: ['text'],
  template: '<div class="hello">{{ text }}</div>',
});

const vm = new HelloCtor({
  data: {
    text: 'HI :)'
  }
});

/*
How can I do something like this?

vue.add(vm);
vue.remove(vm);

*/

代码基本上是为自己说话

那么,是否可以(以及如何?)动态添加和删除Vue.js组件到Vue?

1 个答案:

答案 0 :(得分:1)

您需要在模板中放置vm的位置。然后,您可以$mount手动将组件vm.$mount('el')添加到vm.$destroy(true)的元素。您也可以使用(vm.$el).remove()删除该元素。 Destroy不会从DOM中删除该元素。您需要使用$destroy()

等手动执行此操作

我不是100%这是你正在寻找的东西,当你发现自己手动调用<div id="fui"> <button @click="make">Make</button> <button @click="bye">destroy</button> <div id="mountme"></div> </div> <script> const HelloCtor = Vue.extend({ props: ['text'], template: '<div class="hello">This has been {{ text }}</div>', }) const vm = new HelloCtor ({ data: { text: "Mounted" } }) var vue = new Vue({ el: "#fui", template: ``, methods: { make: () => { vm.$mount('#mountme') }, bye: () => { vm.$destroy(true); (vm.$el).remove();} } }) </script> 时,你可能没有做正确的事......但它确实让你控制了创造和破坏组件。

这样的东西会让你创建然后摧毁你的组件(注意在这种情况下,一旦你摧毁它已经消失了):

//Requesting permission
private void requestWritePermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_SMS) == PackageManager.PERMISSION_GRANTED)
        return;

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_SMS)) {
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }
    //And finally ask for the permission
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_SMS}, WRITE_SMS_PERMISSION_CODE);
}