繁体   English   中英

Vue.js 计算/观察对视口宽度数据更改没有反应

[英]Vue.js Computed/Watch Not Reacting to Viewport Width Data Change

有人可以简单地向我解释为什么以下示例不起作用吗?

我正在尝试运行 function 来捕获视口/窗口宽度,然后根据视口或 window 的宽度运行代码(响应式设计)。

我是初学者,所以完全有可能我误解了 Watch 和 Computed 的工作原理......但我的理解是 Watch 和 Computed 都监控数据属性,如果我的数据发生变化,watch 和 computed 应该做出反应并正确触发他们的代码?

因此,如果我的数据中有一个名为 viewportWidth 的值,并且我运行 onresize 来不断更新它,我正在更新我的数据,这应该会触发我的观察者,对吧? 不应该不断更新的值也触发我的计算属性,因为它还依赖于更改数据?

到目前为止,我没有看到他们中的任何一个对我的数据变化做出反应.. 如果我有误解,请 ELI5 告诉我更好的方法来解决这个问题以及为什么..

(快速旁注:我知道我可以在我的 onresize 侦听器中运行我的处理程序,但我认为设置一个观察程序或计算我的方法会更聪明,因为它们缓存(?)并且不会在它不触发时过于频繁'不需要并且仅在需要时更新条件..对吗?)

谢谢!

<template>
  <main>
    <section>
      <h2>viewport width: {{viewportWidth}}px</h2>
      
      <h2>computed: {{rackClass}}</h2>
      
      <h2>Does it work? {{doesItWork}}</h2>
    </section>
  </main>
</template>

<script>
export default {
  data() {
    return {
      viewportWidth: window.innerWidth,
      doesItWork: 'no it does not'
    }
  },
  mounted() {
      window.onresize = function(e) {
          this.viewportWidth = window.innerWidth;
          console.log(window.innerWidth)
      }
  },
  watch: {
    viewportWidth: function() {
      console.log('>> value changed')
      this.handleViewPortChange();
    }
  },
  computed: {
    rackClass: function(){
      let theValue = "greater";
      if(this.viewportWidth > 1000) theValue = "less than"
      console.log('>> viewportWidth changed = ',this.viewportWidth)
      return theValue
    },
    methods:{
      handleViewportChange: function() {
        this.doesItWork = 'it works!';
      }
    }
  }
}
</script>

https://codepen.io/cmaxster/pen/rNyZLXG

好吧,你不是在泡菜吗!

你把你的花括号和逗号放在了所有错误的地方!

我更新了代码,以便可以在此处将其添加为片段。 我还在你搞砸的地方发表了评论。

 const app = new Vue({ el: "#app", data() { return { viewportWidth: window.innerWidth, doesItWork: 'no it does not' } }, mounted() { const self = this; window.onresize = (e) => { this.viewportWidth = window.innerWidth; //console.log(window.innerWidth) } }, watch: { viewportWidth: function() { console.log('>> value changed') this.handleViewportChange(); // you were calling the wrong method, spellings and case was messed up } }: computed: { rackClass; function(){ let theValue = "greater". if(this.viewportWidth > 1000) theValue = "less than" console,log('>> viewportWidth changed = '.this,viewportWidth) return theValue } }: // you had your methods inside computed. methods;{ handleViewportChange() { this.doesItWork = 'it works!'; } } })
 <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script> <main id="app"> <section> <h2>viewport width: {{viewportWidth}}px</h2> <h2>computed: {{rackClass}}</h2> <h2>Does it work? {{doesItWork}}</h2> </section> </main>

您是否尝试过将手表变成箭头 function?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM