vue中通过变量名的字符串,来获取变量并使用

如,有一变量isshow,通过this[`${"isshow"}`]可以获取到变量。

例,原:this.isshow = false ,现:this[`${"isshow"}`] = false 。

switch1(param) {

      this[`${param}`] = !this[`${param}`];

}

<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引入Vue -->
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>

<body>
    <div id="app" style="height: 600px; width: 500px; margin: 0 auto; display: flex; flex-direction: column;  align-items:center;">

        <div  style="height: 100px; width: 100px; margin-top: 60px;">
            <div v-show="isshow" style="height: 100px; width: 100px; background-color: aqua;"></div>
        </div>

        <button  v-on:click="switch1('isshow')"  style="height: 50px; width: 80px; margin-top: 30px;"></button>

    </div>

    <script>
        new Vue({
            el: '#app',
            data: {
                isshow: true
            },
            methods: {
                switch1(param) {
                    this[`${param}`] = !this[`${param}`];
                    console.log("" + param + " : " + this.isshow)
                }
            }
        });
    </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/u013595395/article/details/99674755