【问题标题】:Vue.js don't work with external JSON in HTML fileVue.js 不适用于 HTML 文件中的外部 JSON
【发布时间】:2018-06-21 21:18:06
【问题描述】:

我想从一个 var 的外部 JSON 文件中获取数据。我认为问题在于我使用 in-html vue.js 和 Vue.js 不明白我为他写的内容:joy: 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
            }
        }
    });

我要做什么? :(

【问题讨论】:

  • 我在 HTML 文件中使用 Vue.js

标签: javascript html css json vue.js


【解决方案1】:

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

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

选项 1: 将您的 script 更改为包含 type="module",并确保在导入路径中使用相对路径。 demo

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

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

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

<!-- 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>

或者,您可以切换到 vue-cli 项目,其中包括在其构建中进行转译,允许您将 imports 用于外部 JSON 文件。 demo

【讨论】:

    猜你喜欢
    • 2012-12-06
    • 2015-03-11
    • 2023-03-29
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 2020-05-15
    • 1970-01-01
    相关资源
    最近更新 更多