首页 > 解决方案 > Vuejs - 焦点元素检查

问题描述

我有这个代码:

<template>
  <div id="app">
    <span
      contenteditable="true"
      spellcheck="false"
      style="width: 800px; display: block"
      :v-text="textEl"
      @focus="focused = true"
      @blur="focused = false"
    />
    {{ focused }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      focused: false,
      textEl: null,
    };
  },
  methods: {
    start() {
      if (this.focused) {
        this.textEl = "text with focus";
      } else {
        this.textEl = "text with not focus";
      }
    },
    mounted() {
      this.start();
    },
  },
  components: {},
};
</script>

完整代码

当跨度集中时,我设置focusedtrue,但是,为什么该方法start不运行?

我需要显示"text with focus"元素何时聚焦,"text with not focus"何时元素未聚焦。我该怎么做?方法start在里面不起作用mounted

标签: javascriptvue.js

解决方案


仅在安装组件时调用该方法。

您要么需要创建start一个观察者,以便它在focused更改时运行:

watch: {
    focused(newVal) {
        if (newVal) {
            this.textEl = "text with focus";
        } else {
            this.textEl = "text with not focus";
        }
    }
}

或调用start事件处理程序:

@focus="start()"
@blur="start()"
...
start() {
    this.focused = !this.focused;

    if (this.focused) {
        this.textEl = "text with focus";
    } else {
        this.textEl = "text with not focus";
    }
},

推荐阅读