当我在 Vue.js 中使用作用域的 css 时,“this”在模板中变得未定义

When I use scoped css in Vue.js, "this" becomes undefined in template

提问人:Ludwig HENRIQUES 提问时间:5/25/2021 更新时间:5/25/2021 访问量:301

问:

当我在 scoped 中设置我的 vue 组件的 css 样式时,我不再有权访问模板中的“this”,但在我的脚本中可以。 我收到以下错误消息: “未捕获(在 promise 中)TypeError:无法读取未定义的属性”$store“” 我需要它,因为我正在使用商店查看示例代码。 提前感谢您的帮助。


export default ({
    name: "ModelSelect",
    computed: {
      modelList: {
        get () {
          return this.$store.state.identification.modelList
        }
      },
      model: {
        get () {
          return this.$store.state.identification.model.id
        },
        set (value) {
          this.$store.dispatch('identification/updateModel', value)
        }
      },
    },
    updated() {
      this.$emit('scrollToNext')
    }
})
</script>

<template>
  <div class="form-select-section mb-5 border p-4" v-if="modelList.length > 0 && this.$store.state.identification.brand.id">
    <span class="text-gray-700 mb-3 block">Choix du modèle</span>
    <ul class="select-group grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 xl:grid-cols-8 gap-4">
      <li class="select-item" v-for="modelItem in modelList" :key="modelItem.attributes.name+modelItem.id">
        <input type="radio" name="model" :value="modelItem.id" v-model="model" :id="modelItem.attributes.name+modelItem.id" class="hidden">
        <label :for="modelItem.attributes.name+modelItem.id" class="flex flex-col items-center justify-center text-center">
          <span class="mt-1">{{modelItem.attributes.name}}</span>
        </label>
      </li>
    </ul>
  </div>
</template>

<style scoped>
  .select-item {
    color: red;
  }
</style>
javascript css vue.js 范围

评论

3赞 Phil 5/25/2021
无论如何,您都不应该在模板中使用。只需使用thisv-if="modelList.length > 0 && $store.state.identification.brand.id"
0赞 Ludwig HENRIQUES 5/25/2021
它确实有效,在我看来,它似乎已经测试过了。非常感谢菲尔,很抱歉这个愚蠢的问题。
0赞 Phil 5/25/2021
对我来说,这是一个很常见的错误,所以我有一个预设的回应,所以不,一点也不愚蠢

答: 暂无答案