为了让用户和应用进行交互,我们可以用 v-on指令添加一个事件监听器,通过它调用在实例中定义的方法:

<div id="event-handling">
  <p>{{ message }}</p>
  <button v-on:click="reverseMessage">反转 Message</button>
</div>
<script>
  const EventHandling = {
    data() {
      return {
        message: 'Hello Vue.js!'
      }
    },
    methods: {
      reverseMessage() {
        this.message = this.message
          .split('')
          .reverse()
          .join('')
      }
    }
  }

  Vue.createApp(EventHandling).mount('#event-handling')
</script>

Untitled

注意在这个方法中,我们更新了应用的状态,但没有触碰 DOM——所有的 DOM 操作都由 Vue 来处理,你编写的代码只需要关注逻辑层面即可。

Vue 还提供了 v-model 指令,它能轻松实现表单输入和应用状态之间的双向绑定。

<div id="two-way-binding">
  <p>{{ message }}</p>
  <input v-model="message" />
</div>
<script>
  const TwoWayBinding = {
    data() {
      return {
        message: 'Hello Vue!'
      }
    }
  }

  Vue.createApp(TwoWayBinding).mount('#two-way-binding')
</script>

Untitled