Vue 2.5从零开始学习 — v-if,v-show,v-f

2018-12-17  本文已影响0人  路万奇与青川君

Vue 的 v-if,v-show,v-for 指令

文档警告 Warning:

由于做笔记没有注意到 Vue 官方文档中的提示、书写规范,之前在 Vue 实例对象中,data 的写法是有误的。

从本页文档开始将使用通行写法。

When defining a component, data must be declared as a function that returns the initial data object, because there will be many instances created using the same definition. If we use a plain object for data, that same object will be shared by reference across all instances created! By providing a data function, every time a new instance is
created we can call it to return a fresh copy of the initial data.

v-if 与 v-show

按照惯例,我们依然从一个需求引入我们的知识点:

页面上有一个按钮,我想让他控制某个内容元素是否显示,在 Vue 我该怎么做呢?

1545043084227.png
    <div id="root">
        <div>Hello world</div>
        <button > show or hide </button>
    </div>

    <script>
        new Vue({
            el: "#root",
            data() {
                return {
                    show: true
                }
            },
            methods: {
                // ...About button action
            }
        })
    </script>
<button @click="handleClick"> </button>

<!-- 此处简写 Vue 实例对象中的 method 部分 -->
    <script>
    methods:{
        handleClick: function(){
            this.show = !this.show //取反
        }
    }
    </script>

那 v-if 和 v-show 有什么区别呢 ?我们按下 F12,打开集成查看器一探究竟吧!

当我们使用 v-if 时:

    <div v-if="show">Hello world</div>
    <button @click="handleClick"> show or hide </button>
1545043084227.png

当我们点击按钮后:

1545043134772.png

而当我们使用 v-show 时:

    <div v-show="show">Hello world</div>
    <button @click="handleClick"> show or hide </button>

当我们点击按钮后:

1545043283315.png

根据情况而定:

v-for

学过一个或多个编程语言后,对 for 一定不陌生,应该几乎是所有的编程语言都把 for 定为了一个和循环相关的关键字,当然在 Vue 中也沿用了这种标示。

比如我有一组数据想要罗列展示,显然手打一行一行地敲成 HTML 文档内容是一个非常麻烦低效的选择。

那么学习了 Vue ,我们可以这样做:

    <div id="root">
        <ul>
            <li v-for="item of list"> {{ item }}</li>
        </ul>
    </div>

    <script>
        new Vue({
            el: "#root",
            data() {
                return {
                    show: true,
                    list: ['Head title', 'Main context', 'End message']
                }
            }
        })
    </script>
上一篇 下一篇

猜你喜欢

热点阅读