本文介绍了如何仅使用 vue 从外部文件将数据加载到 vue.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的这个 vue 示例中,我试图仅使用 vue 从外部 js 文件加载图像"数组.我尝试了类似于这篇文章的内容:我如何从请在 Vue.js 中添加一个外部文件?但这对我来说并不是很有效(很可能是因为我在做一些明显的错误).非常感谢任何有关如何使其工作的建议.

我为您创建了一个 codePen,以防您更喜欢以这种方式查看它.谢谢!https://codepen.io/FloydGekko/pen/eLoRBQ

<风格>[v-披风] {显示:无;}.imageBlock{宽度:100%;边距:10px;}div.宝丽来{宽度:310px;高度:440px;边距:10px;背景颜色:白色;box-shadow: 6px 4px 8px 0 rgba(0, 0, 0, 0.2), 6px 6px 20px 0 rgba(0, 0, 0, 0.19);底边距:25px;边框半径:18px}div.container {文本对齐:居中;填充:10px 20px;}</风格><身体><div id="vue" v-cloak><h2 align="center">展示<select v-model="currentKind" @change="onChange"><option v-for="kind, index in kind" :value="kind" :key="`kind_${index}`">{{kind ?种类:'种类...'}}</option></选择><select v-model="currentColor" @change="onChange"><option v-for="color, index in colors" :value="color" :key="`kind_${index}`">{{color ?颜色:'颜色...'}}</option></选择>和<select v-model="currentShape" @change="onChange"><option v-for="shape, index in shape" :value="shape" :key="`kind_${index}`">{{shape ?形状:'形状...'}}</option></选择><同位素id="root_isotope"参考=同位素":options='选项':list="图像"对齐=中心"><div class="polaroid" align="center"v-for="(image, index) in images"类=图像块":key="image.id"><a target="_blank" :href="image.url"><img border="0" :src="image.pic" alt=""风格="边框半径:20px;显示:块;左边距:自动;右边距:自动;宽度:100%;"></a><div class="容器"><a target="_blank" :href="image.url"><h3 align="center">{{image.title}}</h3></a>

</同位素><h2 align="center"><button @click="reset">显示所有</button>

<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><脚本>让 currentKind = null;让 currentColor = null;让 currentShape = null;var vm = new Vue({el: '#vue',数据() {返回 {当前种类:'',当前颜色:'',当前形状:'',选项: {itemSelector: ".imageBlock",获取排序数据:{身份证:身份证"},sortBy : "id",获取过滤器数据:{查找器:函数(itemElem){让 kindSearch = currentKind ?itemElem.kind.indexOf(currentKind) !== -1 : true;让 colorSearch = currentColor ?itemElem.color.indexOf(currentColor) !== -1 : true;让 shapeSearch = currentShape ?itemElem.shape.indexOf(currentShape) !== -1 : true;返回 kindSearch &&颜色搜索&&形状搜索},},},//这是我试图从外部文件加载的数组图片: [{编号:1,种类:['A'],颜色:['绿色','蓝色'],形状:['方形'],图片:'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',网址:'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',标题:'A',},{编号:2,种类:['B'],颜色:['绿色','红色'],形状:['圆形'],图片:'https://www.kimballstock.com/pix/DOG/05/DOG-05-JE0078-01P.JPG',网址:'https://www.kimballstock.com/pix/DOG/05/DOG-05-JE0078-01P.JPG',标题:'B',},],};},计算:{种类(){让 allTags = _.flatten(this.images.map(image => image.kind))返回 [''].concat(_.uniq(allTags))},颜色(){让 allTags = _.flatten(this.images.map(image => image.color))返回 [''].concat(_.uniq(allTags))},形状(){让 allTags = _.flatten(this.images.map(image => image.shape))返回 [''].concat(_.uniq(allTags))},},方法: {onChange:函数(){currentColor = this.currentColor;currentShape = this.currentShape;currentKind = this.currentKind;this.$refs.isotope.filter('Finder');this.$refs.cpt.layout('packery');},重启(){当前颜色 = '';当前形状 = '';当前种类 = '';this.currentColor = '';this.currentShape = '';this.currentKind = '';this.onChange()}},});</html>

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

解决方案

这实际上取决于外部"的含义,以及仅 Vue"的含义.如果您可以控制数据、结构和位置,您可以执行类似@softbear 所做的操作 - 只需 import 项目中的 javascript 文件即可.根据您的设置,您可以通过多种方式执行此操作.他的例子包括

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

它导出一些东西

window.images = [{'图像数组':'转到这里'}]

如果您使用的是 Vue,您应该能够使用引导项目并直接从您的源文件中导入它.

你可以有一个提供相同结果的后端,浏览器会在导入脚本时自动加载它.

方法有很多种,但结果都是一样的.这里最重要的是这个文件必须声明你以后应该使用的变量.

顶部的方法有几个问题:您无法完全控制何时开始加载数据,也无法完全控制数据何时加载(有一些方法可以做到这一点,但更难且非常难看);有些跨域服务不允许直接执行js代码,只能提供数据.

这意味着,如果您最终遇到这种情况(例如连接到一组动态数据而不是硬编码数据),最好发出加载此数据的请求.基本上手动做浏览器可以为你做的事情.但通过这种方式,您可以完全(且轻松)控制何时以及如何完成.

同样有很多方法 - 如果您在现代浏览器中使用最新的 JS,您可以使用 fetch API,或者使用一些外部工具,比如 axios.

我会投票支持第二种方法,尽管它可能会为您的项目添加另一个依赖项.

in this vue example down below I'm trying to load the 'images' array from an external js file using vue only.I tried something similar to this post:How do I access data from an external file in Vue.js please?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. Thanks!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

解决方案

It really depends on what "external" means, and what "Vue only" means. 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. 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.

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.


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.

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.

I would vote for the second approach, despite it might add another dependency to your project.

这篇关于如何仅使用 vue 从外部文件将数据加载到 vue.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-02 23:55