【问题标题】:Computed properties not triggering except when I open Vue dev tools除非我打开 Vue 开发工具,否则不会触发计算属性
【发布时间】:2019-12-29 06:58:19
【问题描述】:

我有一个着陆页,在里面我用一个v-for迭代了3个option div,每个div从着陆组件接收到它们对应的props,我传递的一个prop是一个name prop,当你点击选定的 div 会发出具有该属性的事件,并且还会重定向到 main 组件,该组件会根据名称填充。

//option div
export default {
  props:['name'],
  data(){
    return {

      }
    }
  },
 methods: {
   selectName() {
     let name = this.name
     this.$eventHub.$emit("select-name", name);
   }

main 组件中,我监听挂载事件,并在组件标题中使用该信息:

mounted: function() { 
  this.$eventHub.$on("select-name", name => { 
    this.$store.dispatch("information/getInfoByName", name); 
    this.title = name
} })

我想添加一个验证,如果用户直接转到https://example.com/main 而不先选择option div,那么我希望它返回到登录页面:

data() {
 name: null
},
computed:{
  nameValidation(){
    if(this.name == null) {
     swal({
     text: "Please select a name first",
     icon: "warning",
     buttons: false,
     timer: 1500
     });

     setTimeout(function () {
       document.location.href = '/landing'
     }, 1500);
   }

它工作...当我打开 Vue 开发工具时,但当我关闭它时,它不起作用。它以某种方式执行计算的属性。我尝试将它用作一种方法并在我的页面标题中调用它 <h1>{{nameValidation}}<h1> 但它总是将 this.name 检查为 null 即使您选择了一个选项,我猜它与我的调度有关在 main 组件的挂载上做,我的问题是为什么计算只使用 devtools 打开?

【问题讨论】:

  • 你在使用 Vue 路由器吗?
  • 是的,landing 和 main 都是不同的路径。
  • 如何将name 传递到主页?
  • 与 vuex ...mapGetters({ getClusterInfo: "getClusterInfo/getClusterInfo" }),
  • 您能否提供在您的数据中设置名称属性的代码?上面的代码使它看起来好像 name 从未更改为任何值。 (另一个问题是您确实不应该在计算属性中处理此逻辑,而是在生命周期挂钩中处理)

标签: vue.js computed-properties


【解决方案1】:

尝试在页面组件的mounted钩子中做,像这样:

...
props: {
  name: {
    type: String,
    required: true
  }
},
mounted() {
  if (this.name == null) {
    swal({
      text: 'Please select a name first',
      icon: 'warning',
      buttons: false,
      timer: 1500,
    })

    setTimeout(() => {
      document.location.href = '/landing'
      // this.$router.push('/landing') // uncomment if you are using Vue Router
    }, 1500)
  }
},
...

【讨论】:

  • 验证失败,即使你选择了一个选项也会返回登陆
猜你喜欢
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-10
  • 2018-12-29
  • 2011-12-13
  • 2020-12-03
  • 2018-12-07
相关资源
最近更新 更多