天天看点

vue template 里使用可选链操作符( ?. )报错:Errors compiling template:invalid expression: Unexpected token ‘.‘ i

问题

我使用的node 版本是 ​

​12.13.0​

​​,vue 版本是 ​

​2.6.11​

​,在 vue template 里使用可选链操作符( ​

​?.​

​ )报错如下:

<template>
    <div id="app">
        <h1>可选链操作符</h1>
        <div>{{testObj?.blog1?.name}}</div>
    </div>
</template>

<script>export default {
    name: "App",
    data() {
        return {
            testObj: {}
        }
    },
    mounted() {
        this.testObj = {
            blog: {
                name: "kaimo313"
            }
        }
    },
};</script>      
vue template 里使用可选链操作符( ?. )报错:Errors compiling template:invalid expression: Unexpected token ‘.‘ i

在 script 里添加是不报错的

<template>
    <div id="app">
        <h1>可选链操作符</h1>
    </div>
</template>

<script>
export default {
    name: "App",
    data() {
        return {
            testObj: {
                blog: {
                    name: "kaimo313"
                }
            }
        }
    },
    created() {
        console.log("blog1--->", this.testObj?.blog1?.name)
        console.log("name1--->", this.testObj?.blog?.name1)
        console.log("kaimo313--->", this.testObj?.blog?.name)
    }
};
</script>      
vue template 里使用可选链操作符( ?. )报错:Errors compiling template:invalid expression: Unexpected token ‘.‘ i

解决

这个问题主要是 vue ​

​2.6.11​

​​ template 不支持可选链操作符,在可以升级 vue 版本的情况下,我们可以升级到 ​

​2.7.0​

​​ 版本,同时 node 版本升级到 ​

​14.0.0​

​。

npm      
vue template 里使用可选链操作符( ?. )报错:Errors compiling template:invalid expression: Unexpected token ‘.‘ i

然后通过 nvm 工具切换版本到 ​

​14.0.0​

​​,nvm 工具的使用可以参考我之前的博客:​​怎么使用 nvm 控制 nodejs 版本切换?​​

vue template 里使用可选链操作符( ?. )报错:Errors compiling template:invalid expression: Unexpected token ‘.‘ i

大家也可以测试其他的版本,我试了一下 ​

​14.0.0​

​以上的几种版本都是可以的,安装切换完版本,然后运行服务,即可

vue template 里使用可选链操作符( ?. )报错:Errors compiling template:invalid expression: Unexpected token ‘.‘ i

页面也可以正常展示了:我们加一行代码:

<template>
    <div id="app">
        <h1>kaimo test 可选链操作符</h1>
        <div>{{testObj?.blog1?.name}}</div>
        <h2>{{testObj?.blog?.name}}</h2>
    </div>
</template>

<script>export default {
    name: "App",
    data() {
        return {
            testObj: {}
        }
    },
    mounted() {
        this.testObj = {
            blog: {
                name: "kaimo313"
            }
        }
    },
};</script>      
vue template 里使用可选链操作符( ?. )报错:Errors compiling template:invalid expression: Unexpected token ‘.‘ i

注意问题

一定要确定好 vue 版本的问题,可以去依赖里面看看版本,​

​2.7.10​

​ 我也测试了一下,也是可行的

vue template 里使用可选链操作符( ?. )报错:Errors compiling template:invalid expression: Unexpected token ‘.‘ i

另外就是版本的问题了:​​node.js模块依赖及版本号​​

vue template 里使用可选链操作符( ?. )报错:Errors compiling template:invalid expression: Unexpected token ‘.‘ i

继续阅读