简体   繁体   English

如何仅使用vue从外部文件将数据加载到vue.js

[英]How to load data into vue.js from an external file using vue only

in this vue example down below I'm trying to load the 'images' array from an external js file using vue only. 在下面的这个vue示例中,我试图仅使用vue从外部js文件中加载“ images”数组。 I tried something similar to this post: How do I access data from an external file in Vue.js please? 我尝试了类似于本文的内容: 如何从Vue.js中的外部文件访问数据? but it's not quite working for me (most likely because I'm doing something obvious wrong). 但这对我来说并不是很有效(很可能是因为我做错了明显的事情)。 Any advice on how to make that work very much appreciated. 非常感谢任何有关如何使该工作有效的建议。

I created a codePen for you in case you prefer to look at it this way. 我为您创建了一个codePen,以防您喜欢这样看。 Thanks! 谢谢! https://codepen.io/FloydGekko/pen/eLoRBQ https://codepen.io/FloydGekko/pen/eLoRBQ

<head>
    <style>
        [v-cloak] {
          display: none;
        }

        .imageBlock{
            width:100%;
            margin:10px;
        }
        div.polaroid {
            width:310px;
            height:440px;
            margin:10px;
            background-color: white;
            box-shadow: 6px 4px 8px 0 rgba(0, 0, 0, 0.2), 6px 6px 20px 0 rgba(0, 0, 0, 0.19);
            margin-bottom: 25px;
            border-radius: 18px
        }
        div.container {
            text-align: center;
            padding: 10px 20px;
        }
    </style>
</head>

<body>

<div id="vue" v-cloak>
    <h2 align="center">
        Show
    <select v-model="currentKind" @change="onChange">
        <option v-for="kind, index in kinds" :value="kind" :key="`kind_${index}`">{{kind ? kind : 'kind...'}}</option>
    </select>
    <select v-model="currentColor" @change="onChange">
        <option v-for="color, index in colors" :value="color" :key="`kind_${index}`">{{color ? color : 'color...'}}</option>
    </select>
        and
     <select v-model="currentShape" @change="onChange">
        <option v-for="shape, index in shapes" :value="shape" :key="`kind_${index}`">{{shape ? shape : 'shape...'}}</option>
    </select>
    </h2>

    <isotope
            id="root_isotope"
            ref="isotope"
            :options='options'
            :list="images"
            align="center">
        <div class="polaroid" align="center"
            v-for="(image, index) in images"
            class="imageBlock"
            :key="image.id">
            <a target="_blank"  :href="image.url"><img border="0" :src="image.pic" alt=""
            style="
                border-radius: 20px;
                display: block;
                margin-left: auto;
                margin-right: auto;
                width: 100%;">
            </a>
            <div class="container">
                <a target="_blank"  :href="image.url">
                <h3 align="center">{{image.title}}</h3>
                </a>
            </div>
        </div>
    </isotope>
    <h2 align="center">
        <button @click="reset">Show all</button>
    </h2>
</div>


<script src='https://unpkg.com/vue/dist/vue.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js'></script>
<script src='https://npmcdn.com/isotope-layout@3.0.6/dist/isotope.pkgd.min.js'></script>
<script src='https://rawgit.com/David-Desmaisons/Vue.Isotope/master/src/vue_isotope.js'></script>


<script>
    let currentKind = null;
    let currentColor = null;
    let currentShape = null;

    var vm = new Vue({
        el: '#vue',
        data() {
            return {
                currentKind:'',
                currentColor:'',
                currentShape:'',
                options: {
                    itemSelector: ".imageBlock",
                    getSortData: {
                      id: "id"
                    },
                    sortBy : "id",
                    getFilterData: {
                        Finder: function(itemElem) {
                            let kindSearch = currentKind ? itemElem.kind.indexOf(currentKind) !== -1 : true;
                            let colorSearch = currentColor ? itemElem.color.indexOf(currentColor) !== -1 : true;
                            let shapeSearch = currentShape ? itemElem.shape.indexOf(currentShape) !== -1 : true;
                            return kindSearch && colorSearch && shapeSearch
                        },
                    },
                },

        //THIS IS THE ARRAY IM TRYING TO LOAD FROM AN EXTERNAL FILE
                images: [
                    {
                        id: 1,
                        kind: ['A'],
                        color: ['Green', 'Blue'],
                        shape: ['Square'],
                        pic: 'http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg',
                        url: 'http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg',
                        title: 'A',
                    },
                    {
                        id: 2,
                        kind: ['B'],
                        color: ['Green', 'Red'],
                        shape: ['Circle'],
                        pic: 'https://www.kimballstock.com/pix/DOG/05/DOG-05-JE0078-01P.JPG',
                        url: 'https://www.kimballstock.com/pix/DOG/05/DOG-05-JE0078-01P.JPG',
                        title: 'B',
                    },
                ],

            };
        },
        computed: {
            kinds(){
                let allTags = _.flatten(this.images.map(image => image.kind))
                return [''].concat(_.uniq(allTags))
            },
            colors(){
                let allTags = _.flatten(this.images.map(image => image.color))
                return [''].concat(_.uniq(allTags))
            },
            shapes(){
                let allTags = _.flatten(this.images.map(image => image.shape))
                return [''].concat(_.uniq(allTags))
            },
        },
        methods: {
            onChange: function() {
                currentColor = this.currentColor;
                currentShape = this.currentShape;
                currentKind = this.currentKind;

                this.$refs.isotope.filter('Finder');
                this.$refs.cpt.layout('packery');
            },
            reset(){
                currentColor = '';
                currentShape = '';
                currentKind = '';

                this.currentColor = '';
                this.currentShape = '';
                this.currentKind = '';
                this.onChange()
            }
        },
    });
</script>
</body>
</html>

https://codepen.io/FloydGekko/pen/eLoRBQ https://codepen.io/FloydGekko/pen/eLoRBQ

It really depends on what "external" means, and what "Vue only" means. 它实际上取决于“外部”的含义和“仅Vue”的含义。 If you have control over the data, it's structure and it's location, you can do something like what @softbear has done - just import a javascript file inside your project. 如果您可以控制数据,数据的结构和位置,则可以执行@softbear所做的事情-只需在项目中import javascript文件即可。 You can do it in numerous ways depending on your setup. 您可以根据设置以多种方式执行此操作。 His example consists of 他的例子包括

<script src="images.js"></script>

which exports something along the lines of 出口的东西沿着

window.images = [{ 'array of images': 'goes here'}]

If you're using Vue you should be able to use the bootstrapped project and just import this from your source files directly. 如果您使用的是Vue,则应该能够使用引导项目,并直接从源文件中导入该项目。

You can have a backend that provides the same result, and the browser will automatically load it when importing the script. 您可以有一个提供相同结果的后端,并且导入脚本时浏览器会自动加载它。

There are numerous ways but the result is the same. 有很多方法,但是结果是相同的。 The most important thing here is that this file must declare your variable that should be used later on. 这里最重要的是,此文件必须declare您的变量,以后应使用。


There are few problems with the approach on top: you don't have full control of when to start loading the data, nor when the data is loaded (there are ways to do that, but harder and pretty ugly); 上面的方法几乎没有问题:您无法完全控制何时开始加载数据,也没有完全控制何时加载数据(有多种方法可以执行此操作,但是更加困难且难看)。 some cross domain serves don't allow you to execute js code directly - they can only provide data. 某些跨域服务不允许您直接执行js代码-它们只能提供数据。

Which means that if you end up in this situation (like connecting to a dynamic set of data and not a hardcoded one), it's always better to make a request to load this data. 这意味着,如果最终遇到这种情况(例如,连接到动态数据集而不是硬编码数据集),最好提出请求以加载此数据。 Basically manually doing what the browser can do for you. 基本上是手动执行浏览器可以为您完成的工作。 But this way you have full (and easy) control of when and how this is done. 但是通过这种方式,您可以完全(轻松)地控制何时以及如何完成此操作。

Again there are numerous ways - if you're using latest JS in a modern browser you can use the fetch API , or use some external tools like axios . 再次有很多方法-如果您在现代浏览器中使用最新的JS,则可以使用fetch API或使用一些外部工具,例如axios

I would vote for the second approach, despite it might add another dependency to your project. 我会投票支持第二种方法,尽管它可能会给您的项目增加另一个依赖性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM