vue3 watch 异步方法

vue3 异步加载中使用 watch

异步数据的加载 Vue 通过 watch 选项提供了一个更通用的方法,来响应数据的变化。

以下实例我们使用 axios 库,后面会具体介绍。

<script src="https://cdn.staticfile.org/vue/3.2.36/vue.global.min.js"></script>
<script src="~/js/Compententysub.js"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<style>
    .class1 {
        background: #444;
        color: #eee;
    }
</style>
<div id="watch-example">
  <p>
    输入一个问题,以 ? 号结尾输出答案:
    <input v-model="question" />
  </p>
  <p>{{ answer }}</p>
</div>  
<script>
const watchExampleVM = Vue.createApp({
   data() {
      return {
         question: '',
         answer: '每个问题结尾需要输入 ? 号。'
      }
   },
   watch: {
      // 每当问题改变时,此功能将运行,以 ? 号结尾,兼容中英文 ?
      question(newQuestion, oldQuestion) {
         if (newQuestion.indexOf('?') > -1 || newQuestion.indexOf('?') > -1) {
            this.getAnswer()
         }
      }
   },
   methods: {
      getAnswer() {
         this.answer = '加载中...'
         axios
            .get('/try/ajax/json_vuetest.php')
            .then(response => {
            this.answer = response.data.answer
         })
            .catch(error => {
            this.answer = '错误! 无法访问 API。 ' + error
         })
      }
   }
}).mount('#watch-example')
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值