Vue照着文档巧的一些案例 不包含组件

Vue简单的案例

参考 https://cn.vuejs.org/v2/guide

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
  <!-- 1 文本插值 -->
    <div id="app">
        {{ message }}
    </div>


    <!--2 绑定元素 attribute -->
    <div id="app-2">
      <span v-bind:title="message">
        鼠标悬停几秒钟查看此处动态绑定的提示信息!
      </span>
    </div>


<!-- 3 控制切换一个元素是否显示 -->
    <div id="app-3">
      <p v-if="seen">现在你看到我了</p>
    </div>

<!--4 v-for 渲染数组-->

<div id="app-4">
  <ol>
    <li v-for = "todo in todos">
      {{todo.text}}
    </li>
  </ol>
</div>

<!-- 5 处理用户输入 -->

<div id="app-5">
  <p>{{message}}</p>
  <button v-on:click="reverseMessage">反转消息</button>
</div>

<!--6 v-model 指令,它能轻松实现表单输入和应用状态之间的双向绑定。 -->
<div id="app-6">
  <p>{{message}}</p>
  <input v-model = "message">
</div>


<!-- -------------------------------------------------------------------------------------------------------------------------------- -->
    <script>
    // 1 <!-- 可以打开js控制台 修改 app.message 当前页面会变化 -->
    var app = new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue!'
      }
    })
    //2
    var app2 = new Vue({
      el: '#app-2',
        data: {
          message: '页面加载于 ' + new Date().toLocaleString()
        }
    })
    //3 继续在控制台输入 app3.seen = false,你会发现之前显示的消息消失了。
    var app3 = new Vue({
      el: '#app-3',
      data: {
        seen: true
      }
    })
    //4 绑定数组的数据 控制台输入 app4.todos.push({ text: '新项目' }) 会新增一个
    var app4 = new Vue({
      el:"#app-4",
      data:{
        todos:[
          {text: "学习 JavaScript"},
          {text: "学习 Vue"},
          {text: "整个项目"}
        ]
      }
    })

    // 5 编写翻转消息函数
    var app5 = new Vue({
      el:"#app-5",
      data:{
        message: "Hello Vue.js!"
      },
      //注意在 reverseMessage 方法中,我们更新了应用的状态,
      //但没有触碰 DOM——所有的 DOM 操作都由 Vue 来处理,你编写的代码只需要关注逻辑层面即可。
      methods: {
        reverseMessage: function() {
          this.message = this.message.split('').reverse().join('')
        }
      }
    })
     //6
     var app6 = new Vue({
       el:"#app-6",
       data: {
         message: 'Hello Vue!'
       }
     })

    </script>
</body>
</html>

计算属性和侦听器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
    <!-- 1 计算属性 -->
    <!-- 2计算属性缓存 vs 方法 调用方法需要加上括号  reversedMessage() -->
    <div id="example">
        <p>Original message: "{{ message }}"</p>
        <p>Computed reversed message: "{{ reversedMessage1 }}"</p>
        <p>Reversed message : "{{ reversedMessage() }}"</p>
    </div>
    <!-- 计算属性是基于它们的响应式依赖进行缓存的。只在相关响应式依赖发生改变时它们才会重新求值。
        这就意味着只要 message 还没有发生改变,多次访问 reversedMessage 计算属性会立即返回之前的计算结果,而不必再次执行函数。 -->


    <!-- 3计算属性 vs 侦听属性 -->
    <!-- 侦听属性。当你有一些数据需要随着其它数据变动而变动时,你很容易滥用 watch——特别是如果你之前使用过 AngularJS。
        然而,通常更好的做法是使用计算属性而不是命令式的 watch 回调 -->

    <!-- 4  计算属性的 setter -->
    <!-- 
        computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}
现在再运行 vm.fullName = 'John Doe' 时,setter 会被调用,vm.firstName 和 vm.lastName 也会相应地被更新。

     -->


     <!-- 侦听器 -->
     <div id="watch-example">
        <p>
          Ask a yes/no question:
<!--  v-model 指令,它能轻松实现表单输入和应用状态之间的双向绑定 -->
          <input v-model="question">
        </p>
        <p>{{ answer }}</p>
      </div>

<!-- -------------------------------------------------------------------------------------------------------------------------------- -->

<script>
    //1 计算属性
    var vm = new Vue({
        el:"#example",
        data:{
            message: "Hello"
        },
        computed:{
            //计算属性的getter
            reversedMessage1: function() {
                return this.message.split('').reverse().join('')
            }
        },
        methods:{
            reversedMessage: function(){
                return this.message.split('').reverse().join('')
            }
        }
    })
    //你可以打开浏览器的控制台,自行修改例子中的 vm。vm.reversedMessage 的值始终取决于 vm.message 的值。

// <!-- 3计算属性 vs 侦听属性 -->
    // var vm = new Vue({
    //     el: '#demo',
    //     data: {
    //         firstName: 'Foo',
    //         lastName: 'Bar',
    //         fullName: 'Foo Bar'
    //     },
    //     //侦查 firstname和 lastname变化执行下面的函数
    //     watch: {
    //         firstName: function (val) {
    //         this.fullName = val + ' ' + this.lastName
    //         },
    //         lastName: function (val) {
    //         this.fullName = this.firstName + ' ' + val
    //         }
    //     }
    // })
    //用计算属性代替
    // var vm = new Vue({
    //     el: '#demo',
    //     data: {
    //         firstName: 'Foo',
    //         lastName: 'Bar'
    //     },
    //     computed: {
    //         fullName: function () {
    //         return this.firstName + ' ' + this.lastName
    //         }
    //     }
    // })


</script>
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
<script>
var watchExampleVM = new Vue({
  el: '#watch-example',
  data: {
    question: '',
    answer: 'I cannot give you an answer until you ask a question!'
  },
  watch: {
    // 如果 `question` 发生改变,这个函数就会运行
    question: function (newQuestion, oldQuestion) {
      this.answer = 'Waiting for you to stop typing...'
      this.debouncedGetAnswer()
    }
  },
  created: function () {
    // `_.debounce` 是一个通过 Lodash 限制操作频率的函数。
    // 在这个例子中,我们希望限制访问 yesno.wtf/api 的频率
    // AJAX 请求直到用户输入完毕才会发出。想要了解更多关于
    // `_.debounce` 函数 (及其近亲 `_.throttle`) 的知识,
    // 请参考:https://lodash.com/docs#debounce
    this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
  },
  methods: {
    getAnswer: function () {
      if (this.question.indexOf('?') === -1) {
        this.answer = 'Questions usually contain a question mark. ;-)'
        return
      }
      this.answer = 'Thinking...'
      var vm = this
      axios.get('https://yesno.wtf/api')
        .then(function (response) {
          vm.answer = _.capitalize(response.data.answer)
        })
        .catch(function (error) {
          vm.answer = 'Error! Could not reach the API. ' + error
        })
    }
  }
})
</script>
</body>


</html>

Class 与 Style 绑定

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

</head>
<style>
    .active {
        color: pink
    }
    .text-danger {
        border-bottom:1px solid #F00
    }
</style>
<body>
    <div v-bind:class="{ active: isActive }"></div>

    <div id = 'name'
  class="static"
  v-bind:class="{ active: isActive, 'text-danger': hasError }"
>111111</div>
<!-- -------------------------------------------------------------------------------------------------------------------------------- -->

<script>
    var vm = new Vue({
        el: '#name',
        data:{
            isActive:true,
            hasError:true
        }
    })

</script>

</body>


</html>

事件处理

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>事件处理</title>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="../js/vue.js"></script>
</head>
<body>
<!-- v-on监听DOM时间,在触发时运行js代码 -->
<div id="example-1">
    <button v-on:click = "counter += 1">Add 1</button>
    <p>The button above has been clicked {{ counter }} times.</p>
</div>



<!-- 2 事件处理方法 -->
<div id = "example-2">
    <!-- `greet` 是在下面定义的方法名 -->
    <button v-on:click = 'greet'>Greet</button>
</div>

<!--3 内联处理器中的方法  -->
<div id="example-3">
    <button v-on:click ="say('hi')">Say hi</button>
    <button v-on:click="say('what')">Say what</button>
    
<!-- 有时也需要在内联语句处理器中访问原始的 DOM 事件。可以用特殊变量 $event 把它传入方法: -->

    <button v-on:click="warn('Form cannot be submitted yet.', $event)">
        Submit
    </button>
</div>
<!-- 4 事件修饰符 -->
<!-- Vue.js 为 v-on 提供了事件修饰符。之前提过,修饰符是由点开头的指令后缀来表示的。

.stop
.prevent
.capture
.self
.once
.passive -->

<!-- 阻止单击事件继续传播 -->
<a v-on:click.stop="doThis"></a>

<!-- 提交事件不再重载页面 -->
<form v-on:submit.prevent="onSubmit"></form>

<!-- 修饰符可以串联 -->
<a v-on:click.stop.prevent="doThat"></a>

<!-- 只有修饰符 -->
<form v-on:submit.prevent></form>

<!-- 添加事件监听器时使用事件捕获模式 -->
<!-- 即内部元素触发的事件先在此处理,然后才交由内部元素进行处理 -->
<div v-on:click.capture="doThis">...</div>

<!-- 只当在 event.target 是当前元素自身时触发处理函数 -->
<!-- 即事件不是从内部元素触发的 -->
<div v-on:click.self="doThat">...</div>

<!-- 2.1.4新增 -->
<!-- 点击事件将只会触发一次 -->
<a v-on:click.once="doThis"></a>


<!-- 滚动事件的默认行为 (即滚动行为) 将会立即触发 -->
<!-- 而不会等待 `onScroll` 完成  -->
<!-- 这其中包含 `event.preventDefault()` 的情况 -->
<div v-on:scroll.passive="onScroll">...</div>
<!-- 这个 .passive 修饰符尤其能够提升移动端的性能。 -->
<!--5  按键修饰符 -->

<!-- 只有在 `key` 是 `Enter` 时调用 `vm.submit()` -->
<input v-on:keyup.enter="submit">

<input v-on:keyup.page-down="onPageDown">
<!-- .exact 修饰符允许你控制由精确的系统修饰符组合触发的事件。 -->

<!-- 即使 Alt 或 Shift 被一同按下时也会触发 -->
<button v-on:click.ctrl="onClick">A</button>

<!-- 有且只有 Ctrl 被按下的时候才触发 -->
<button v-on:click.ctrl.exact="onCtrlClick">A</button>

<!-- 没有任何系统修饰符被按下的时候才触发 -->
<button v-on:click.exact="onClick">A</button>

<!-- -------------------------------------------------------------------------------------------------------------------------------- -->

<script>
 var example1 = new Vue({
     el:"#example-1",
     data:{
         counter: 0
     }
 })


 var example2 = new Vue({
     el:'#example-2',
     data: {
         name: 'Vue.js'
     },
     methods: {
         greet: function(){
         // `this` 在方法里指向当前 Vue 实例
            alert('Hello' +this.name+'!')
                           // `event` 是原生 DOM 事件
            if (event) {
                alert(event.target.tagName)
            }
        }
    }    
 })

 // 也可以用 JavaScript 直接调用方法
// example2.greet() // => 'Hello Vue.js!'

new Vue({
    el:"#example-3",
    methods: {
        say: function(message){
            alert(message)
        },
        warn: function (message, event) {
            // 现在我们可以访问原生事件对象
            if (event) {
            event.preventDefault()
            }
            alert(message)
        }
    }
})
</script>

</body>


</html>

posted @ 2021-12-02 16:35  _Salvatore  阅读(34)  评论(0)    收藏  举报