Vue技术9.5姓名案例_watch实现

<!DOCTYPE html>>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>姓名案例_watch实现</title>
        <!-- 引入Vue -->
        <script type="text/javascript" src="../js/vue.js"></script>
    </head>
    <body>
        <!--
            computed和watch之间的区别:
                1.computed能完成的功能,watch都可以完成。
                2.watch能完成的功能,computed不一定能完成,例如:watch可以进行异步操作。
            两个重要的小原则:
                1.所被Vue管理的函数,最好写成普通函数,这样this的指向才是vm或组件实例对象。
                2.所有不被Vue所管理的函数(定时器的回调函数,ajax的回调函数等),最好写成箭头函数。
                这样this的指向才是vm或组件实例对象。
        -->
        <!-- 准备好一个容器 -->
        <div id="root">
            姓:<input type="text" v-model="lastname"><br/><br/>
            名:<input type="text" v-model="firstname"><br/><br/>
            全名:<span>{
   
   {fullname}}</span>

        </div>
    </body>

    <script type="text/javascript">
        Vue.config.productionTip = false
        
        const vm = new Vue({
      
      
            el:'#root',
            data:{
      
      
                lastname:'张',
                firstname:'三',
                fullname:'张-三'
            },
           watch:{
      
      
            lastname(val){
      
      
                this.fullname = val + '-' + this.firstname
            },
            firstname(val){
      
      
                this.fullname = this.lastname + '-' + val
            }
           }
        })
    </script>
</html>

猜你喜欢

转载自blog.csdn.net/qq_40713201/article/details/126168189
9.5