简体   繁体   English

将 Stripe JS 集成到 Laravel 6.0:[Vue 警告]:编译模板时出错:

[英]Integrating Stripe JS into Laravel 6.0: [Vue warn]: Error compiling template:

I have my Stripe.js integration in my checkout.blade.php file.我的 checkout.blade.php 文件中有我的 Stripe.js 集成。 It works but not without this error:它有效但并非没有此错误:

[Vue warn]: Error compiling template:

Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed

I have made the error disappear but then the Stripe Element won't appear on the page.我已使错误消失,但随后条纹元素不会出现在页面上。 I also have other JS integrated in this file for my form validation that works fine and doesn't return an error.我还在这个文件中集成了其他 JS 用于我的表单验证,它可以正常工作并且不会返回错误。

Here is the Stripe code that returns an error:这是返回错误的 Stripe 代码:

<script>
        (function(){
        // Create a Stripe client.
        var stripe = Stripe('pk_test_9dn1vt3i0j0Q5GZdwAXn9iUs00iMziQDyD');

        // Create an instance of Elements.
        var elements = stripe.elements();

        // Custom styling can be passed to options when creating an Element.
        // (Note that this demo uses a wider set of styles than the guide below.)
        var style = {
        base: {
            color: '#32325d',
            fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
            fontSmoothing: 'antialiased',
            fontSize: '16px',
            '::placeholder': {
            color: '#aab7c4'
            }
        },
        invalid: {
            color: 'red',
            iconColor: 'red'
        }
        };

        // Create an instance of the card Element.
        var card = elements.create('card', { style: style, hidePostalCode: true });

        // Add an instance of the card Element into the `card-element` <div>.
        card.mount('#card-element');

        // Handle real-time validation errors from the card Element.
        card.addEventListener('change', function(event) {
        var displayError = document.getElementById('card-errors');
        if (event.error) {
            displayError.textContent = event.error.message;
        } else {
            displayError.textContent = '';
        }
        });

        // Handle form submission.
        var form = document.getElementById('payment-form');
        form.addEventListener('submit', function(event) {
        event.preventDefault();

        stripe.createToken(card).then(function(result) {
            if (result.error) {
            // Inform the user if there was an error.
            var errorElement = document.getElementById('card-errors');
            errorElement.textContent = result.error.message;
            } else {
            // Send the token to your server.
            stripeTokenHandler(result.token);
            }
        });
        });

        // Submit the form with the token ID.
        function stripeTokenHandler(token) {
        // Insert the token ID into the form so it gets submitted to the server
        var form = document.getElementById('payment-form');
        var hiddenInput = document.createElement('input');
        hiddenInput.setAttribute('type', 'hidden');
        hiddenInput.setAttribute('name', 'stripeToken');
        hiddenInput.setAttribute('value', token.id);
        form.appendChild(hiddenInput);

        // Submit the form
        form.submit();
        }
        })();
    </script>

Note that right now that the Stripe code is nested into my:请注意,现在 Stripe 代码嵌套在我的:

@section('content')

@endsection

which is extended by my parent template, '''app.blade.php'''.这是由我的父模板扩展的,'''app.blade.php'''。

If I paste it outside the parent template and wrap it with something like this:如果我将它粘贴到父模板之外并用这样的东西包装它:

@section('stripe')

@endsection

then no error returns but the element won't appear because my JS doesn't know where to mount my Stripe element.然后没有错误返回但该元素不会出现,因为我的 JS 不知道在哪里安装我的 Stripe 元素。 Of course, I had this in my parent template too: @yield('stripe')当然,我的父模板中也有这个: @yield('stripe')

How can I get my Stripe Element to appear without getting this templating error?如何在不出现此模板错误的情况下显示我的条纹元素?

EDIT: I used the Laravel/ui scaffolding (Bootstrap version).编辑:我使用了 Laravel/ui 脚手架(Bootstrap 版本)。 Attached are the following:附上以下内容:

app.js:应用程序.js:

require('./bootstrap');

window.Vue = require('vue');

const app = new Vue({
    el: '#app',
});

ExampleComponent.vue:示例组件.vue:

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Example Component</div>

                    <div class="card-body">
                        I'm an example component.
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Component mounted.')
        }
    }
</script>

Thanks谢谢

As you mention in your question, you're using the bootstrap scaffolding from laravel/ui .正如您在问题中提到的,您正在使用laravel/ui的引导脚手架。 Depending on the commands you used to generate that scaffolding, it can install some VueJS-centric files or data into common files, which appears to have happened with you.根据您用于生成该脚手架的命令,它可以将一些以 VueJS 为中心的文件或数据安装到公共文件中,这似乎发生在您身上。 While you yourself did nothing with VueJS, the scaffolding did it for you.虽然你自己没有用 VueJS 做任何事情,但脚手架为你做了。

In your app.js file, if you remove or comment-out lines 3-7, and re-run laravel-mix:app.js文件中,如果删除或注释掉第 3-7 行,并重新运行 laravel-mix:

require('./bootstrap');

// 3 window.Vue = require('vue');
// 4
// 5 const app = new Vue({
// 6    el: '#app',
// 7 });

You will solve your problem.你会解决你的问题。

As shown on line 6, VueJS targets the app id'd element which is present in app.stub , which is a file that is normally put under resources/views/layouts/app.blade.php ;如行6所示,VueJS靶向app id'd元件,其存在于app.stub ,其是下正常放文件resources/views/layouts/app.blade.php ; this view is used as the base view to extend other views from.此视图用作扩展其他视图的基础视图。 Given that the app id'd div encapsulates most of the page/body element, any content you put inside of it VueJS will interpret as part of it's base template.鉴于app id 的 div 封装了大部分 page/body 元素,您放入其中的任何内容 VueJS 都将解释为它的基本模板的一部分。 This is why your error warns not to "put script tags inside the template".这就是为什么您的错误警告不要“将脚本标签放入模板中”。

As said, the above changes to your app.js file will of course solve the problem, as it takes VueJS out of the equation.如上所述,对app.js文件的上述更改当然可以解决问题,因为它将 VueJS 排除在外。 That said, however, if you don't plan on using VueJS at all, you could also remove it from your package.json file and run npm prune to remove unused packages(as in any package not specified in package.json and not required as a dependency of another package), to remove the library from your site entirely.也就是说,如果你根本不打算使用 VueJS,你也可以从你的package.json文件中删除它并运行npm prune来删除未使用的包(如在package.json未指定且不需要的任何包中)作为另一个包的依赖项),从您的站点完全删除库。

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

相关问题 Laravel Nova 覆盖 vue 组件导致 [Vue 警告]:编译模板时出错 - Laravel Nova override vue component resulting [Vue warn]: Error compiling template 编译模板时出错:组件模板需要根元素,而不仅仅是 vue.js 和 laravel 中的文本 - Error compiling template: Component template requires a root element, rather than just text in vue.js with laravel 仅在IE11上的VUE JS模板编译错误 - VUE JS template compiling error just on IE11 任何<script> tag in my blade file cause a [Vue warn]: Error compiling template, error -- How do I resolve this? - Any <script> tag in my blade file cause a [Vue warn]: Error compiling template, error -- How do I resolve this? 使用字符串模板将来自laravel的路由值与样式绑定时Vue警告错误 - Vue Warn Error When Binding Route Value from laravel with style using string template 在laravel中编译vue js前端报错 - Error when compiling vue js front end in laravel Laravel - [Vue 警告]:无法挂载组件:未定义模板或渲染函数 - Laravel - [Vue warn]: Failed to mount component: template or render function not defined Laravel Stripe.js错误 - Stripe.js error with Laravel [Vue 警告]:渲染错误:“RangeError: Invalid array length” [Vue JS] - [Vue warn]: Error in render: “RangeError: Invalid array length” [Vue JS] Vue JS中的模板错误 - Template error in vue js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM