Vue.js不能在HTML文件中使用外部JSON

时间:2018-01-12 11:53:01

标签: javascript html css json vue.js

我想从外部JSON文件中获取一个var的数据。我认为问题在于我使用in-html vue.js而Vue.js并不理解我为他写的内容:欢乐: jsfiddle
第二个问题是我无法使用json的值:



new Vue({
        el: '#app',
        data() {
            return {
                searchResult: [],
                search: '',
            }
        },

        created: function() {
            this.searchResult = [
                {
                    "id": 0,
                    "title": "d",
                    "img": "src"
                }
            ];
        },

        computed: {
            filteredName: function() {
                return this.searchResult.filter((x) => {
                    return x.title.match(this.search)
                });
            },
            allOK: function () {
                if (this.search.valueOf() === "") {
                    return false
                } else {
                    return true
                }
            },
            hrefResult: function () {
                return "/item?=" + this.searchResult.id
            }
        }
    });




我要做什么? :(

1 个答案:

答案 0 :(得分:0)

问题是您在module脚本之外使用ECMAScript Importsimport关键字只能在<script type="module">内识别,因此您的使用会导致语法错误:Unexpected identifierimport语句的行上(您尝试导入{ {1}})。

有一些解决方案需要现代浏览器(以及旧版浏览器的polyfill)。

选项1:json/products.json更改为包含script,并确保在导入路径中使用相对路径。 demo

type="module"

选项2:获取外部JSON文件而不是导入它。 demo

<!-- inside HTML file -->
<script type="module">
  import products from './json/products.json.js'

  new Vue({
    el: '#app',
    data () {
      return {
        items: products
      }
    }
  })
</script>

或者,您可以切换到vue-cli项目,其中包括在其构建中进行转换,允许您将<!-- inside HTML file --> <script> (async () => { const productsResponse = await fetch('./json/products.json'); const products = await productsResponse.json(); new Vue({ el: '#app', data () { return { items: products } } }) })(); </script> 用于外部JSON文件。 demo