VueJS如何在方法中访问Mounted()变量

Jon*_*han 0 vue.js

我是Vue的新手,并希望获得有关如何访问和使用在Mounted()我的方法中创建的变量的帮助。

我有这个代码

模板

<select class="controls" @change="getCatval()">
Run Code Online (Sandbox Code Playgroud)

脚本

mounted() {
    var allcards = this.$refs.allcards;
    var mixer = mixitup(allcards);
  },
methods: {
    getCatval() {
      var category = event.target.value;
      // I want to access mixer here;
    }
  }
Run Code Online (Sandbox Code Playgroud)

除了这个示例,我无法在其他地方找到解决方案,在该示例中,我可以调用method xfrom mounted()并将其传递给混音器,然后在我内部使用getCatval()

有没有更简单的方法来访问这些变量?

小智 5

我首先建议您停止使用var,并使用最新的let和const声明变量

您必须先在中声明一个变量

data(){
 return {
   allcards: "",
   mixer: ""
 }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的mount()中

mounted() {
     this.allcards = this.$refs.allcards;
    this.mixer = mixitup(this.allcards);
  },
methods: {
    getCatval() {
      let category = event.target.value;

     this.mixer
    }
  }
Run Code Online (Sandbox Code Playgroud)

  • 无论如何,this。$ refs都不是反应性的,因此不需要将其缓存到已挂载的生命周期挂钩上的数据存储中。只要做`this.mixer = mixitup(this。$ refs.allcards)`就足够了。 (2认同)