【问题标题】:How to run a function in Vue.js when state changes状态变化时如何在 Vue.js 中运行函数
【发布时间】:2019-05-02 19:18:21
【问题描述】:

我希望在我的 Vue 应用程序中的状态发生变化时运行一个函数。 在我的组件中,我可以获得 isOpen 的布尔状态。我希望运行一个函数,当模式打开并且 isOpen 设置为 true 时,该函数将焦点添加到我的表单输入。我试过使用观察者,但没有运气。我通过在 html 中调用 :class="{ 'is-open': search.isOpen }" 并通过 css 显示它来打开我的模式。任何帮助将不胜感激。

data() {
    return {
      isFocussed: this.$store.state.search,
      //checks the state of isOpen?
    }
  },

  computed: {
    search() { return this.$store.state.search },
  },

  watch: {
    isFocussed() {
     this.formfocus()
    },
  },

  methods: {
    formfocus() {
      document.getElementById('search').focus()
    },

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    请查看我的 sn-p,它显示了在 Vue.js 中工作的好方法,您可以使用非常有用的 refs 而不是 document.getElementById()

    new Vue({
      el: '#app',
      data: {
        isOpen: false,
      },
      computed: {
        
      },
      watch: {
        isOpen(){
          if(this.isOpen){
            this.$nextTick( function () {
                this.formfocus();
              }
            );
          }
        }
      },
      methods: {
        formfocus(){
          this.$refs.search.focus();
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
    
    <div id="app">
      <button v-on:click="isOpen = !isOpen">show modal</button>
      <div v-if="isOpen">
        <input ref="search" type="text" placeholder="search">
      </div>
    </div>

    编辑:我在手表上添加了条件 if,我希望这可以解决问题

    【讨论】:

    • 感谢 Zouheir。但是,我从 $nextTick 行收到“警告意外未命名函数”错误?
    【解决方案2】:

    我不确定您的模板是什么样的,但这是我将焦点设置在条件元素上的方式。

    元素

    <input type="text" class="search-input" v-model="search" :class="{'collapsed-search': hideInput}" placeholder="Enter keyword" ref="search">
    

    注意输入中的ref="search"

    这里是输入条件为真时的方法

    toggleSearch() {
      this.hideInput = !this.hideInput
       this.search = ''
       setTimeout(() => {
          this.$refs.search.focus()
      }, 1000)
    }
    

    this.$refs.search.focus() 在元素完全创建后调用,这是setTimeout 的目的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      • 2023-03-06
      • 1970-01-01
      相关资源
      最近更新 更多